开发者

Singleton and thread safety

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开发者_如何学Python? What if MyApp does not spawn threads?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜