单例和线程安全

发布于 2024-11-19 13:23:23 字数 794 浏览 1 评论 0原文

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

以此为例,假设我有一个使用单例的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柒七 2024-11-26 13:23:23

在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文