Simple Deadlock Examples

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

    Here's a simple deadlock in C#.

    void UpdateLabel(string text) {
       lock(this) {
          if(MyLabel.InvokeNeeded) {
            IAsyncResult res =  MyLable.BeginInvoke(delegate() {
                 MyLable.Text = text;
                });
             MyLabel.EndInvoke(res);
            } else {
                 MyLable.Text = text;
            }
        }
    }
    

    If, one day, you call this from the GUI thread, and another thread calls it as well - you might deadlock. The other thread gets to EndInvoke, waits for the GUI thread to execute the delegate while holding the lock. The GUI thread blocks on the same lock waiting for the other thread to release it - which it will not because the GUI thread will never be available to execute the delegate the other thread is waiting for. (ofcourse the lock here isn't strictly needed - nor is perhaps the EndInvoke, but in a slightly more complex scenario, a lock might be acquired by the caller for other reasons, resulting in the same deadlock.)

提交回复
热议问题