Double-checked locking in .NET

2019-01-02 20:35发布

I came across this article discussing why the double-check locking paradigm is broken in Java. Is the paradigm valid for .NET (in particular, C#), if variables are declared volatile?

8条回答
像晚风撩人
2楼-- · 2019-01-02 21:08

I've gotten double-checked locking to work by using a boolean (i.e. using a primitive to avoid the lazy initialisation):

The singleton using boolean does not work. The order of operations as seen between different threads is not guaranteed unless you go through a memory barrier. In other words, as seen from a second thread, created = true may be executed before instance= new Singleton();

查看更多
闭嘴吧你
3楼-- · 2019-01-02 21:11

Implementing the Singleton Pattern in C# talks about this problem in the third version.

It says:

Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!

The author seems to imply that double locking is less likely to work than other strategies and thus should not be used.

查看更多
登录 后发表回答