pulsejet
pulsejet

Reputation: 1223

Two threads modifying same object at same time

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

Answers (2)

Nipun
Nipun

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

Rene
Rene

Reputation: 2466

  1. Yes.
  2. Depends on the operation. If both threads modify the key structure of the map, i.e. insert or delete an entry, then the map can become invalid.
  3. You need to prevent parallel write access to the map. Also no read access should happen while a write access is in progress. Look at read-write-mutexes or -spinlocks.

Upvotes: 1

Related Questions