Threads and simple Dead lock cure

前端 未结 9 667
余生分开走
余生分开走 2021-01-04 22:48

When dealing with threads (specifically in C++) using mutex locks and semaphores is there a simple rule of thumb to avoid Dead Locks and have nice clean Synchronization?

9条回答
  •  被撕碎了的回忆
    2021-01-04 23:21

    A good simple rule of thumb is to always obtain your locks in a consistent predictable order from everywhere in your application. For example, if your resources have names, always lock them in alphabetical order. If they have numeric ids, always lock from lowest to highest. The exact order or criteria is arbitrary. The key is to be consistent. That way you'll never have a deadlock situation. eg.

    1. Thread 1 locks resource A
    2. Thread 2 locks resource B
    3. Thread 1 waits to obtain a lock on B
    4. Thread 2 waits to obtain a lock on A
    5. Deadlock

    The above can never happen if you follow the rule of thumb outlined above. For a more detailed discussion, see the Wikipedia entry on the Dining Philosophers problem.

提交回复
热议问题