开发者

Is it good to test a condition then lock then re-test the condition [duplicate]

开发者 https://www.devze.com 2023-02-12 00:24 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Double-checked locking in .net
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Double-checked locking in .net

EDIT: lots of edits to clarify this question is not about singleton

I find myself writing code like this:

    if(resourceOnDiskNeedsUpdating)
  开发者_StackOverflow社区  {
        lock(lockObject)
        {
            if(resourceOnDiskNeedsUpdating) // has a previous thread already done this?
                UpdateResourceOnDisk();
        }
    }
    return LoadResourceFromDisk();

UpdateResource() is a slow operation. Does this pattern make sense?

Are there better alternatives?


This called "double-checked locking".

You need a memory fence to make it correct.

See Wikipedia's article on double checked locking in .NET


An alternative I use would be to just use the 'volatile' keyword. http://msdn.microsoft.com/en-us/library/x13ttww7%28v=vs.71%29.aspx

0

精彩评论

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