I would like to explain threading deadlocks to newbies. I have seen many examples for deadlocks in the past, some using code and some using illustrations (like the famous 4
Here's a simple example in C++11.
#include // mutex
#include // cout
#include // getchar
#include // this_thread, yield
#include // async
#include // seconds
using namespace std;
mutex _m1;
mutex _m2;
// Deadlock will occur because func12 and func21 acquires the two locks in reverse order
void func12()
{
unique_lock l1(_m1);
this_thread::yield(); // hint to reschedule
this_thread::sleep_for( chrono::seconds(1) );
unique_lock l2(_m2 );
}
void func21()
{
unique_lock l2(_m2);
this_thread::yield(); // hint to reschedule
this_thread::sleep_for( chrono::seconds(1) );
unique_lock l1(_m1);
}
int main( int argc, char* argv[] )
{
async(func12);
func21();
cout << "All done!"; // this won't be executed because of deadlock
getchar();
}