Moti
Moti

Reputation: 927

Lock map and vector from accessing from two threads

I have two threads, each of which has a function that manipulates the same std:map and std:vector variables.

What is the best way to keep these variables.

Thanks

Upvotes: 0

Views: 420

Answers (2)

Neel Basu
Neel Basu

Reputation: 12904

There is no universal best way. You need to sanitize all read/write calls to your synchronized structure through one functions that locks/unlocks mutex accordingly. You might have multiple functions but they should all operate on the same common mutex.

Its better to have a storage class and keep the map and vector as private member variables. and write forwarding functions in that class that locks/unlocks the mutex and forwards the read/write call to actual map or vector. then you have limited number of doors to access actual structures. and it will be easier to manage.

You may use boost::mutex as member variable of that class.

Upvotes: 0

TemplateRex
TemplateRex

Reputation: 70526

It depends on the kind of manipulations. Do you only overwrite the stored values, or do you also insert / remove elements? In the former case you could lock only a specific element of the container (e.g. by embedding a std::mutex inside each element), whereas in the latter case you need to lock the entire container during each manipulation.

Upvotes: 1

Related Questions