单例多线程 [英] Singleton & Multi-threading

查看:157
本文介绍了单例多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类

class Singleton
{
  private:

    static Singleton *p_inst;
    Singleton();

  public:

    static Singleton * instance()
    {
      if (!p_inst)
      {
        p_inst = new Singleton();
      }

      return p_inst;
    }
};

请详细说明在多线程环境中实现Singleton时采取的预防措施。

Please do elaborate on precautions taken while implementing Singleton in multi-threaded environment .

推荐答案

在多线程中,子句

if(!p_inst)
{
    p_inst = new Singleton();
}

实际上是3个单独的操作。您获得 p_inst 的值,设置 p_inst 的值,并写入 p_inst 。所以get-set-write意味着你需要在 p_inst 上加锁,否则你可以有两个线程创建 Singleton

is actually 3 separate actions. You are getting the value of p_inst, setting the value of p_inst and writing the value of p_inst. So get-set-write means that you need to put a lock around p_inst otherwise you can have 2 threads which create a Singleton value that each thread uses.

这里是如何查看问题,假设你的 Singleton 可变字段 val

Here is how you can view the issue, assume that your Singleton has a mutable field val:

thread A -> p_inst is NULL
    thread B -> p_inst is NULL
       thread A -> set to Singleton (1)
           thread B -> set to Singleton (2)
              thread C -> p_inst is Singleton (2)
                  thread A -> set val to 4
                      thread B -> set val to 6
                         thread C -> get val (it's 6)
                             thread A -> get val (it's 4!!)

你看到了吗?有一个Singleton的两个副本漂浮,没有一个知道对方。检查 Singleton 的第三个线程只会看到最后一个赋值。但是使用锁定,您可以防止多个分配和这些类型的问题。

You see? There's 2 copies of a Singleton floating about, neither of which knows about the other. The third thread which checks on the Singleton is only going to see the last assignment. But with locking, you can prevent multiple assignment and these types of problems.

这篇关于单例多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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