mercredi 30 mars 2022

Data race about map::operator[]

Is there any potential problem in this code snippet?

#include <mutex>
#include <map>
#include <vector>
#include <thread>

constexpr int FOO_NUM = 5;

int main()
{
std::map<int, std::mutex> mp;

std::vector<std::thread> vec;
for(int i=0; i<2; i++)
{
    vec.push_back(std::thread([&mp](){
    std::lock_guard<std::mutex> lk(mp[FOO_NUM]); //I think there is some potential problem here, am I right?
    //do something
     }));
}

for(auto& thread:vec)
{
thread.join();
}

As per the document,which says that:

Inserts value_type(key, T()) if the key does not exist. This function is equivalent to return insert(std::make_pair(key, T())).first->second;

I think there is a potential problem in the aforementioned code snippet. You see this may happen:

1.the first thread created a mutex, and is locking the mutex.

2.the second thread created a new one, and the mutex created in the first thread needs to be destroyed while it's still used in the first thread.

Aucun commentaire:

Enregistrer un commentaire