developer tip

잠금 개체가 정적이어야하는 이유는 무엇입니까?

copycodes 2020. 8. 14. 07:54
반응형

잠금 개체가 정적이어야하는 이유는 무엇입니까?


다중 스레딩에서 잠금을 위해 개인 정적 읽기 전용 개체를 사용하는 것은 매우 일반적입니다. 개인은 캡슐화를 조여 잠금 개체에 대한 진입 점을 줄이고 따라서 가장 필수적인 항목에 액세스 할 수 있음을 이해합니다.

하지만 왜 정적일까요?

private static readonly object Locker = new object();

마지막에 필드는 내 클래스 내에서만 사용되며 대신 이것을 사용할 수도 있습니다.

private readonly object Locker = new object();

다른하실 말씀 있나요?

최신 정보:

예를 들어이 코드를 붙여 넣었습니다 (예제). 나는 이것에 정적 또는 비 정적 사물함을 사용할 수 있으며 둘 다 잘 작동합니다. 아래의 답변을 고려할 때 내 사물함을 이와 같이 정의해야합니까? (미안하지만 다음 주에 인터뷰가 있고 모든 세부 사항을 알아야합니다. :)

private readonly object Locker = new object();

다음은 코드입니다.

    private int _priceA;
    private int _priceB;
    private EventWaitHandle[] _waithandle;
    private readonly IService _service;

//ctor
public ModuleAViewModel(IService service)
    {
        _service = service;
        _modelA = new ModelA();
        _waithandle = new ManualResetEvent[2];
        _waithandle[0] = new ManualResetEvent(false);
        _waithandle[1] = new ManualResetEvent(false);
        LoadDataByThread();
    }


 private void LoadDataByThread()
        {
            new Thread(() =>
                           {
                               new Thread(() =>
                               {
                                   lock (Locker)
                                   {
                                       _priceA = _service.GetPriceA();
                                   }
                                   _waithandle[0].Set();
                               }).Start();

                               new Thread(() =>
                               {
                                   lock (Locker)
                                   {
                                       _priceB = _service.GetPriceB();
                                   }
                                   _waithandle[1].Set();
                               }).Start();

                               WaitHandle.WaitAll(_waithandle);
                               PriceA = _priceA;
                               PriceB = _priceB;
                           }).Start();
        }

감사


It isn't "very common to use a private static readonly object for locking in multi threading" - rather, it is common to use a lock at the appropriate / chosen granularity. Sometimes that is static. More often, IMO, it isn't - but is instance based.

The main time you see a static lock is for a global cache, or for deferred loading of global data / singletons. And in the latter, there are better ways of doing it anyway.

So it really depends: how is Locker used in your scenario? Is it protecting something that is itself static? If so, the lock should be static. If it is protecting something that is instance based, then IMO the lock should also be instance based.


It doesn't have to be static, in fact sometimes it should not be static.

The variable should live in the same scope as the methods where you use it for locking. If the methods are static, the variable should be static, and if the methods are instance methods, the variable should be an instance varible.

A static variable will still work when used to lock in an instance method, but then you will be locking too much. You will lock all methods in all instances, not just the methods in the same instance.


The scope and lifetime of a lock can/should depend on the 'thing' you want to lock. Static locks are mostly used to lock static things.

참고URL : https://stackoverflow.com/questions/5053172/why-does-the-lock-object-have-to-be-static

반응형