3 Kasım 2020 Salı

Yazılımda Deadlock

Deadlock Oluşturan Sebepler
Deadlock şu sebeplerden oluşur
1. Mutual Exclusion
2. Incremental Acquisition
3. No preemption
4. Circular Waits
Deadlock 'tan Kaçınma Yöntemleri
Açıklaması şöyle
There are three techniques to prevent deadlocks: 
1) Lock Ordering, 
2) Lock Timeout, and 
3) Deadlock Detection. 
Circular Wait
Burada dikkat edilmesi gereken kural şöyle
Mutex lock ordering rule: Given a total ordering of all mutexes, a program is deadlock-free if each thread acquires its mutexes in order and releases them in reverse order.
Bir başka açıklama şöyle
7.4.4 Circular Wait

The fourth and final condition for deadlocks is the circular-wait condition. One way to ensure that this condition never holds is to impose a total ordering of all resource types and to require that each process requests resources in an increasing order of enumeration.
Yani birden fazla mutex varsa tüm thread'ler aynı sırada lock işlemini yapmalı. Ve tersi sırada unlock işlemi yapılmalı

Örnek - Lock Sırasına Dikkat Edilmemesi
Şu kod deadlock'a sebep olur.
(1)                 |        (2)
  Lock mutex A   (success) |    Lock mutex B   (success)
  Lock mutex B   (wait)    |    Lock mutex A   (wait) 
                           X
                OUCH! DEADLOCK OCCURED
Örnek - Unlock Sırasına Dikkat Edilmemesi
Şu kod deadlock'a sebep olur.
       (1)                 |        (2)
  Lock mutex A   (success) |   Lock mutex A   (wait)
  Lock mutex B   (success) |    
  ....                     |
  Unlock mutex A           |                  (success)
  Relock mutex A (wait)    |   Lock mutex B   (wait)
                           X
                OOPS! I DEADLOCK AGAIN
Örnek - Java
Şu kod deadlock'a sebep olur
void increment(){
  synchronized(lock1){
    synchronized(lock2){
      variable++;
    }
  }
}

void decrement(){
  synchronized(lock2){
    synchronized(lock1){
      variable--;
    }
  }
}

Hiç yorum yok:

Yorum Gönder