Is std::map insert thread safe?

Viewed 425

I know that the std::map class is thread unsafe in read and write in two threads. But is it OK to insert in multiple threads?

void writeMap()
{ 
    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(i, new p(i)));
    }
}

int main()
{
    std::srand((int)std::time(0)); 
    for (int i = 0; i < 1000; ++i)
    {
        long long random_variable = (std::rand()) % 1000;
        std::thread t(writeMap);
        std::cout << "Thread created " << t.get_id() << std::endl;
        t.detach();
    }
    return 0;
}

Like such code is running normal no matter how many times I try.

3 Answers

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

Most standard library types are thread safe only if you are using separate object instances in separate threads. Take a look at the thread safety part of container's docs.

program is complex,to some extent,like magic(LOL). The code run results are different on various IDE. Before, I used VS2013, it's always right. But on vs19 and linux,the result of the same code is wrong. Maybe on vs2013,the implement of MAP has special way.

As @NutCracker has mentioned, std::map::insert is not thread-safe.

But, if the posted code works fine, I think the reason is that the map fills very fast by one thread and as a result, other threads are not modifying the map anymore.

Related