affiliate_link

Saturday, February 27, 2016

Mutithreading FAQs with examples

Deadlock

To further illustrate how a deadlock might occur, imagine the following sequence of events:
  • Thread 1 acquires lock A.
  • Thread 2 acquires lock B.
  • Thread 1 attempts to acquire lock B, but it is already held by Thread 2 and thus Thread 1 blocks until B is released.
  • Thread 2 attempts to acquire lock A, but it is held by Thread 1 and thus Thread 2 blocks until A is released.
At this point, both threads are blocked and will never wake up

Race Conditions

race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable. Then the first thread and second thread perform their operations on the value, and they race to see which thread can write the value last to the shared variable. The value of the thread that writes its value last is preserved, because the thread is writing over the value that the previous thread wrote.

// Thread 1
   Total = Total + val1
// Thread 2
   Total = Total - val2
Reference: https://support.microsoft.com/en-us/kb/317723

No comments: