4

I have a data structure that has two methods to access it : query() and modify(). Multiple threads can use query() at the same time but only a single thread can enter modify() and at the same time all threads using query() has to exit before access occurs on modify().

What is the best way to make this data structure threadsafe in C++?

(I read up on boost read/write locking but I was told that it could be 3-40x slower than using mutexes)

Phelodas
  • 3,853
  • 5
  • 25
  • 30
  • Try the simplest solution first -- protect all accesses with a mutex. 99.5% of the time, this will be satisfactory and your job will be done. (If it is not possible for one thread to try to modify the object while another thread is, or might be, accessing it, then no locking is needed. This assumes your reads don't modify the object in any way.) – David Schwartz Oct 15 '12 at 09:09
  • It depends what happens in `modify`. The whole point of protecting in both read- and write-sections is to stop a read from being invalid while it's halfway through being changed. Protecting only the `modify` function will not achieve this. However, if you are only protecting a single datatype such as an `int` or a pointer, I believe this can be okay. I would want write an extremely brutal test program to verify that, however. – paddy Oct 15 '12 at 09:11
  • possible duplicate of [Do I need to protect read access to an STL container in a multithreading environment?](http://stackoverflow.com/questions/187583/do-i-need-to-protect-read-access-to-an-stl-container-in-a-multithreading-environ) – Bo Persson Oct 15 '12 at 09:12
  • fwiw, a mutex (on win32/64 at least) will be considerably slower than a crit-sec for quick in-and-out locks. If you're crossing process boundaries, you have no choice there, but if your single-process consider it an option. I'm sure the Linux guys worked that out, at least better than windoze did. – WhozCraig Oct 15 '12 at 09:14

1 Answers1

1

In general you should protect shared data with mutex.

But if type of you shared data is integer you could also consider using std::atomic, which is typically much faster than locking a mutex.

nogard
  • 9,432
  • 6
  • 33
  • 53