Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 820
PapaDiHatti Avatar asked Apr 02 '26 07:04

PapaDiHatti


1 Answers

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.

like image 69
kmdreko Avatar answered Apr 04 '26 12:04

kmdreko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!