Simple Deadlock Examples

后端 未结 28 2236
失恋的感觉
失恋的感觉 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:24

    A sneaky way to deadlock with just a single thread is to try to lock the same (non-recursive) mutex twice. This might not be the simple example you were looking for, but sure enough I encountered such cases already.

    #include 
    #include 
    
    int main()
    {
      std::mutex m;
      m.lock();
      m.lock();
      std::cout << "Expect never to get here because of a deadlock!";
    }
    

提交回复
热议问题