


After all, the only reason for two threads to be synchronized with each other, is to allow them to communicate.

I could go on for a while, but in my experience, the easiest way to work with threads is using patterns that are well-known to everyone who might work with the code, such as the producer/consumer pattern: it's easy to explain and you only need one tool (a queue) to allow your threads to communicate with each other. It makes the architecture easier to work with - especially for some-one who isn't used to concurrency.
#Deadlock avoidance lock ordering code#
try to hide asynchronous behavior: you're usually better hiding your concurrency in your software's architecture, such that most calling code won't care whether there's a thread there or not.One example of this was posted in the C++ Lounge on SO chat a few days ago, by Luc, as an example of this (code at the end of this post): just trying to synchronize on something else that happens to be in the neighborhood doesn't mean your code is correctly synchronized. watch out for race conditions: in C++, nothing will tell you when a given piece of data is shared between threads and you don't use some kind of synchronization on it.don't hold a lock when calling a virtual function: even if at the time you're writing your code you know which function will be called and what it will do, code evolves, and virtual functions are there to be overridden, so ultimately, you won't know what it does and whether it will take any other locks, meaning you will lose your guaranteed order of locking.There are a few other rules you should follow when coding threaded code in C++, though, among which the most important may be: The technique you describe isn't just common: it's the one technique that has been proven to work all the time. My question is what other techniques, patterns or common practices are used in coding to guarantee dead lock prevention? The simple solution is to lock A and then lock B, regardless of the order specific thread will use the resources.ĭo Resource A thing. Locking the resources in the order they are needed causes a dead-lock. The common solution to preventing deadlock in code is to make sure the sequence of locking occur in a common manner regardless of which thread is accessing the resources.įor example given threads T1 and T2, where T1 accesses resource A and then B and T2 accesses resource B and then A.
