PapaDiHatti
PapaDiHatti

Reputation: 1921

std::map insert thread safe in c++11?

I have very simple code in which multiple threads are trying to insert data in std::map and as per my understanding this should led to program crash because this is data race

std::map<long long,long long> k1map;
void Ktask()
{
    for(int i=0;i<1000;i++)
    {
        long long random_variable = (std::rand())%1000;
        std::cout << "Thread ID -> " << std::this_thread::get_id() << " with looping index " << i << std::endl;
        k1map.insert(std::make_pair(random_variable, random_variable));
    }
}


int main()
{
    std::srand((int)std::time(0)); // use current time as seed for random generator
    for (int i = 0; i < 1000; ++i)
    {
           std::thread t(Ktask);
           std::cout << "Thread created " << t.get_id() << std::endl;
           t.detach();
    }

    return 0;
}

However i ran it multiple time and there is no application crash and if run same code with pthread and c++03 application is crashing so I am wondering is there some change in c++11 that make map insert thread safe ?

Upvotes: 3

Views: 5069

Answers (2)

kmdreko
kmdreko

Reputation: 59942

No, std::map::insert is not thread-safe.

There are many reasons why your example may not crash. Your threads may be running in a serial fashion due to the system scheduler, or because they finish very quickly (1000 iterations isn't that much). Your map will fill up quickly (only having 1000 nodes) and therefore later insertions won't actually modify the structure and reduce possibility of crashes. Or perhaps the implementation you're using IS thread-safe.

Upvotes: 5

Nicol Bolas
Nicol Bolas

Reputation: 473312

For most standard library types, the only thread safety guarantee you get is that it is safe to use separate object instances in separate threads. That's it.

And std::map is not one of the exceptions to that rule. An implementation might offer you more of a guarantee, or you could just be getting lucky.

And when it comes to fixing threading bugs, there's only one kind of luck.

Upvotes: 1

Related Questions