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

烂漫一生 提交于 2019-12-22 00:38:19

问题


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)
    {
        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?


回答1:


This called "double-checked locking".

You need a memory fence to make it correct.

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




回答2:


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



来源:https://stackoverflow.com/questions/5036518/is-it-good-to-test-a-condition-then-lock-then-re-test-the-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!