Jake
Jake

Reputation: 11430

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:

Upvotes: 1

Views: 151

Answers (1)

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59885

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.

Upvotes: 1

Related Questions