Under what conditions can a thread enter a lock (Monitor) region more than once concurrently?

前端 未结 6 1917
一个人的身影
一个人的身影 2021-01-05 04:45

(question revised): So far, the answers all include a single thread re-entering the lock region linearly, through things like recursion, where you can trace the steps of a s

6条回答
  •  时光取名叫无心
    2021-01-05 05:02

    One of the more subtle ways you can recurse into a lock block is in GUI frameworks. For example, you can asynchronously invoke code on a single UI thread (a Form class)

    private object locker = new Object();
    public void Method(int a)
    {
        lock (locker)
        {
            this.BeginInvoke((MethodInvoker) (() => Method(a)));
        }
    }
    

    Of course, this also puts in an infinite loop; you'd likely have a condition by which you'd want to recurse at which point you wouldn't have an infinite loop.

    Using lock is not a good way to sleep/awaken threads. I would simply use existing frameworks like Task Parallel Library (TPL) to simply create abstract tasks (see Task) to creates and the underlying framework handles creating new threads and sleeping them when needed.

提交回复
热议问题