Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to protect read access to an STL container in a multithreading environment?

I have one std::list<> container and these threads:

  • One writer thread which adds elements indefinitely.

  • One reader/writer thread which reads and removes elements while available.

  • Several reader threads which access the SIZE of the container (by using the size() method)

There is a normal mutex which protects the access to the list from the first two threads. My question is, do the size reader threads need to acquire this mutex too? should I use a read/write mutex?

I'm in a windows environment using Visual C++ 6.

Update: It looks like the answer is not clear yet. To sum up the main doubt: Do I still need to protect the SIZE reader threads even if they only call size() (which returns a simple variable) taking into account that I don't need the exact value (i.e. I can assume a +/- 1 variation)? How a race condition could make my size() call return an invalid value (i.e. one totally unrelated to the good one)?

Answer: In general, the reader threads must be protected to avoid race conditions. Nevertheless, in my opinion, some of the questions stated above in the update haven't been answered yet.

Thanks in advance!

Thank you all for your answers!

like image 993
davidag Avatar asked Oct 09 '08 14:10

davidag


2 Answers

Yes, the read threads will need some sort of mutex control, otherwise the write will change things from under it.

A reader/writer mutex should be enough. But strictly speaking this is an implmentation-specific issue. It's possible that an implementation may have mutable members even in const objects that are read-only in your code.

like image 53
Michael Burr Avatar answered Oct 08 '22 04:10

Michael Burr


Checkout the concurrent containers provided by Intel's Open Source Threading Building Blocks library. Look under "Container Snippets" on the Code Samples page for some examples. They have concurrent / thread-safe containers for vectors, hash maps and queues.

like image 23
Pat Notz Avatar answered Oct 08 '22 05:10

Pat Notz