【发布时间】: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