Reputation: 1223
In a simple server-client mechanism I'm writing, the server stores a set of key-value mappings in an STL map. For talking to multiple clients, a separate thread is created for each, and I've passed the map to the threads using std::ref (I need a common keystore). While this works, is it possible that:
1) If two clients communicate exactly at the same time, then the two threads will try to modify the map at the same time?
2) In this case, what would happen?
3) What possibly could I do to avoid anything bad?
Upvotes: 0
Views: 1965
Reputation: 2261
1) If two clients communicate exactly at the same time, then the two threads will try to modify the map at the same time?
Yes, they will try to modify at same time
2) In this case, what would happen?
You will have undefined behavior. Anything can happen.
3) What possibly could I do to avoid anything bad?
Use std::lock_guard
to avoid any problem. You can refer this link for more details:
http://en.cppreference.com/w/cpp/thread/lock_guard
Upvotes: 4
Reputation: 2466
Upvotes: 1