单例和线程安全
当谈论单例和有关创建单例实例时的竞争条件的线程安全问题时,我们正在谈论哪个线程?
以此为例,假设我有一个使用单例的 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 这样做怎么办 不产生线程?
When talking about Singletons and threadsafe-ty issues concerning race conditions in creating the singleton instance, which thread are we talking about?
Using this as example, assume I have a MyApp that uses a Singleton
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();
}
}
Is it talking about:
- when I open the MyApp.exe once, and
then once more again, trying to have
both opened? - Or is it talking about the threads spawned by MyApp? What if MyApp does
not spawn threads?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Windows 中 线程仅存在于进程范围内,即应用程序的运行实例。因此,线程安全意味着确保从给定的多个线程中顺序访问共享资源过程。
更一般地说,竞争条件是由于并发而发生的,无论范围如何。例如,如果对资源的访问没有得到适当的监管,向外部进程公开共享资源的分布式应用程序仍然会受到竞争条件的影响。
In Windows threads exist solely within the scope of a process, i.e. the running instance of an application. So thread safety means making sure that shared resources are accessed sequentially from multiple threads within a given process.
In more general terms, race conditions occur as a result of concurrency regardless of scope. For example a distributed application that exposes a shared resource to external processes, is still subject to race conditions if access to that resource isn't properly regulated.