应如何“双重检查锁定”在Delphi中实现? [英] How should "Double-Checked Locking" be implemented in Delphi?

查看:125
本文介绍了应如何“双重检查锁定”在Delphi中实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,以下代码(来自页面)可以用于懒惰以线程安全的方式实例化单例类:

  class Foo {
private volatile Helper helper = null;
public Helper getHelper(){
if(helper == null){
lock(this){
if(helper == null)
helper = new Helper ();
}
}
return helper;
}
}

什么是等效的线程安全的Delphi代码? / p>




该文章还提到了Java中双重检查锁定的两个问题:




  • 在辅助引用指向新创建的对象之前,新对象可能被构造,意味着创建两个对象

  • 它有可能在对象仍在创建时帮助引用指向一个内存块,这意味着对不完整对象的引用将被返回



所以虽然上述文章中的C#和Java版本的代码看起来几乎相同,但只有C#版本可以按预期方式工作。这还有一个额外的问题,如果这两个问题也存在于Delphi版本的Double-Checked Locking?

解决方案

使用System.TMonitor以线程安全的方式锁定对象实例。

  function TFoo.GetHelper():THelper; 
begin
如果没有分配(FHelper)然后
begin
System.MonitorEnter(Self);
尝试
如果没有分配(FHelper)然后
FHelper:= THelper.Create();
finally
System.MonitorExit(Self);
结束
结束
结果:= FHelper;
结束

如需进一步参考,请参阅锁定我的对象...,请! Allen Bauer 。其实,代表。我从这里收集应该去艾伦。


In C#, the following code (from this page) can be used to lazily instantiate a singleton class in a thread safe way:

  class Foo {
        private volatile Helper helper = null;
        public Helper getHelper() {
            if (helper == null) {
                lock(this) {
                    if (helper == null)
                        helper = new Helper();
                }
            }
            return helper;
        }
    }

What would be the equivalent thread safe Delphi code?


The article also mentions two problems with Double Checked Locking in Java:

  • it is possible that the new object is constructed before the helper reference is made to point at the newly created object meaning that two objects are created
  • it is possible that the helper reference is made to point at a block of memory while the object is still being created meaning that a reference to an incomplete object will be returned

So while the code of the C# and the Java version in the mentioned article look almost identical, only the C# version works as expected. Which leads to the additional question if these two problems also exist in a Delphi version of Double-Checked Locking?

解决方案

Use System.TMonitor to lock the object instance in a thread safe way.

function TFoo.GetHelper(): THelper;
begin
  if not Assigned(FHelper) then
  begin
    System.MonitorEnter(Self);
    try
      if not Assigned(FHelper) then
        FHelper := THelper.Create();
    finally
      System.MonitorExit(Self);
    end;
  end;
  Result := FHelper;
end;

For further reference look at Lock my object..., please! from Allen Bauer. In fact, the rep. I gather from this should go to Allen.

这篇关于应如何“双重检查锁定”在Delphi中实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆