Simple Deadlock Examples

后端 未结 28 2292
失恋的感觉
失恋的感觉 2020-11-30 16:28

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

28条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 17:27

    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();
    }
    

提交回复
热议问题