Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Based on runtime environment and the scheduler on the operating system, the following code will have different behaviors. However, with proper timing, the code main() will deadlock when running thr1 and thr2 in which thr1 tries to lock ba2's mutex while thr2 tries to lock on ba1's mutex in the deposit() function and the program will not progress.

...

The solution to the deadlock problem is to lock in predefined order in the deposit() function. In the following example, each thread will lock based on bank_account's id defined in increasing orderthe struct. This way circular wait problem is avoided and when one thread requires a lock will guarantee it will require the next lock.

...