单身和线程安全

时间:2011-07-08 07:08:00

标签: concurrency thread-safety singleton

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

以此为例,假设我有一个使用Singleton的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做了什么 不产生线程?

1 个答案:

答案 0 :(得分:1)

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

更一般地说,竞争条件是由于并发而不考虑范围而发生的。例如,如果未正确管理对该资源的访问,则向共享资源公开外部进程的分布式应用程序仍然会受到竞争条件的影响。

相关问题