Avb Avb
Avb Avb

Reputation: 553

C++ map thread synchronization

I have two threads. Thread1 is incrementing one of its own variables (consumenum) with certain interval. As the same time, I have thread2 which also increments one of thread1's variables (iter->second->producenum). Do I need mutex protections around these variables when I increment them in both threads?

Thread1:

mutex1->lock();
std::map<uint32_t, myframe>::iterator it2 = mymap.find(consumenum);
mylocalframe = it2->second;
mymap.erase (it2);
mutex1->unlock();

consumenum++;

mutex2->lock();
pktctr--;
mutex2->unlock();

Thread2:

std::map<int, Thread1 *>::iterator iter = mythreads.find(id);
iter->second->mutex1->lock();
iter->second->mymap.insert( std::pair<uint32_t,myframe>(iter->second->producenum, myframeval));
iter->second->mutex1->unlock();

iter->second->producenum++;

iter->second->mutex2->lock();
iter->second->pktctr++;
iter->second->mutex2->unlock();

Upvotes: 1

Views: 1219

Answers (3)

Gerald
Gerald

Reputation: 23479

Based on the code you posted, no, you don't need a mutex. A mutex is only required if you are accessing the same data from both threads. Incrementing 2 different integers from 2 different threads is fine, as long as Thread1 is not deleted during the lifetime of Thread2.

Upvotes: 2

GWeuro
GWeuro

Reputation: 353

Yes,you need it.If you handle var1 or var2, you must use a same mutex protections around these variables.

Upvotes: 1

Leo Chapiro
Leo Chapiro

Reputation: 13984

Yes, of course you need it, e.g. critical section:

std::mutex g_i_mutex;

void increment_map(std::map &myMap)
{
    std::lock_guard<std::mutex> lock(g_i_mutex);
    // increment map

    // g_i_mutex is automatically released when lock
    // goes out of scope
}

Upvotes: 2

Related Questions