开发者

lock inside a simple property - can it deadlock?

开发者 https://www.devze.com 2023-04-04 08:17 出处:网络
Questions: Can I deadlock this code? Does the IsMouseInside property is thread safe? Does the use of the copy variable make sense?

Questions:

  1. Can I deadlock this code? Does the IsMouseInside property is thread safe?
  2. Does the use of the copy variable make sense?

PS: UI thread updates IsMouseInside. Another thread will read its value some times

    public Class Test    
    {

    private readonly object isMouseInsideLocker = new object();
    private bool isMouseInside =开发者_如何学Python false;

    public bool IsMouseInside
    {
        get
        {
            bool copy;
            lock (this.isMouseInsideLocker)
                copy = this.isMouseInside;
            return copy;
        }
        set
        {
            lock (this.isMouseInsideLocker)
                this.isMouseInside = value;
        }
    }

    private void lblProcessTime_MouseEnter(object sender, EventArgs e)
    {
        IsMouseInside = true;
    }

    private void lblProcessTime_MouseLeave(object sender, EventArgs e)
    {
        IsMouseInside = false;
    }
}


  1. No, you can't.
  2. It doesn't. Just return isMouseInside;


No that can't deadlock; there is only one lock object, and no extension point exists that would allow you to do something messy while the lock is held. However, if you are using lock you should probably make it clear what scenarios you are trying to avoid. While the meaning is actually very subtle, I wonder whether volatile might work here without needing any locks. Or Interlocked on an int that is always either 0 or 1.

But sure, it looks like it'll work; bool is always atomic anyway, so the lock here is only really acting as a memory-barrier avoiding cache issues (hence why volatile might also work). And remember that any time you get the value, that is now stale and might already be incorrect. It was true at the point of read, though.


  1. You can't deadlock - you are locking on the same object.
  2. It doesn't make sense to me. Also the locking doesn't make sense - I don't think you achieve anything with it.

What is the goal?


You can only have a deadlock if you have two different locks A and B that two different threads try to acquire in different order - since you only have one lock here you are safe.

Also keep in mind that C# lock (which is syntactic sugar for using a Monitor) is reentrant - a single thread cannot deadlock since it can reenter a lock as many times as it wants to once it has initially acquired it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号