use the same lock object at two different code block?

后端 未结 3 1068
温柔的废话
温柔的废话 2020-12-18 18:36

Can I use the same lock object at two methods, accessed by two different threads? Goal is to make task1 and task2 thread safe.

object lockObject = new object         


        
相关标签:
3条回答
  • 2020-12-18 19:30

    If you want to prevent different threads from performing task1 and task2 at the same time, then you must use the same lock object.

    If the two tasks do not contend for the same resources, you could use different lock objects.

    0 讨论(0)
  • 2020-12-18 19:41

    Yes, you can use the same lock object (it's technically a monitor in the computer science sense, and is implemented with calls to methods in System.Monitor) in two different methods.

    So, say that you had some static resource r, and you wanted two threads to access that resource, but only one thread can use it at a time (this is the classic goal of a lock). Then you would write code like

    public class Foo
    {
        private static object _LOCK = new object();
    
        public void Method1()
        {
            lock (_LOCK)
            {
                // Use resource r
            }
        }
    
        public void Method2()
        {
            lock (_LOCK)
            {
                // Use resource r
            }
        }
    }
    

    You need to lock around every use of r in your program, since otherwise two threads can use r at the same time. Furthermore, you must use the same lock, since otherwise again two threads would be able to use r at the same time. So, if you are using r in two different methods, you must use the same lock from both methods.

    EDIT: As @diev points out in the comments, if the resource were per-instance on objects of type Foo, we would not make _LOCK static, but would make _LOCK instance-level data.

    0 讨论(0)
  • 2020-12-18 19:42

    Yes.

    You can and it works. If you don't use the same object, the blocks could execute at the same time. If you do use the same object, they can't.

    Also, you mean lock(lockObject), not using(lockObject).

    0 讨论(0)
提交回复
热议问题