0

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?

pulsejet
  • 1,101
  • 13
  • 27
  • Do the clients write to the key store or only read from it? – MikeMB Aug 18 '17 at 06:08
  • Have a look at [`std::mutex`](http://en.cppreference.com/w/cpp/thread/mutex). They are used to lock certain data to be only processed by one thread at a time. Without locking, accessing data from multiple threads simultaneously will most likely cause undefined behaviour. – muXXmit2X Aug 18 '17 at 06:08
  • 1
    https://stackoverflow.com/questions/15067160/stdmap-thread-safety – Matt Aug 18 '17 at 06:11
  • http://en.cppreference.com/w/cpp/container#Thread_safety – Passer By Aug 18 '17 at 06:13
  • @mikemb, writing and reading both. – pulsejet Aug 18 '17 at 06:25

2 Answers2

4

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

Nipun
  • 2,217
  • 5
  • 23
  • 38
1
  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.
Rene
  • 2,466
  • 1
  • 12
  • 18