【问题标题】:Singleton and thread safety单例和线程安全
【发布时间】:2011-07-08 07:08:00
【问题描述】:

在谈论与创建单例实例时的竞争条件有关的单例和线程安全问题时,我们在谈论哪个线程?

以此为例,假设我有一个使用单例的 MyApp

class MyApp
{
    MySingleton oneAndOnly;

    int main() // application entry point
    {
        oneAndOnly = MySingleton::GetInstance();
    }

    void SpawnThreads()
    {
        for(int i = 0; i < 100; i++)
        {
              Thread spawn = new Thread(new ThreadStart(JustDoIt));
              spawn.Start();
        }
    }

    void JustDoIt()
    {
        WaitRandomAmountOfTime(); // Wait to induce race condition (maybe?) for next line.

        MySingleton localInstance = MySingleton::GetInstance();
        localInstance.DoSomething();
    }
}

是不是在说:

  • 当我打开 MyApp.exe 一次,并且 然后再一次,试图拥有 都打开了?
  • 还是说 MyApp 产生的线程?如果 MyApp 发生了怎么办 不产生线程?

【问题讨论】:

    标签: concurrency thread-safety singleton


    【解决方案1】:

    在 Windows threads exist solely within the scope of a process 中,即应用程序的运行实例。所以thread safety 的意思是确保从给定进程中的多个线程顺序访问共享资源

    在更一般的术语中,无论范围如何,都会发生竞争条件。例如,将共享资源暴露给外部进程的分布式应用程序,如果对该资源的访问没有得到适当的监管,仍然会受到竞争条件的影响。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多