How can I protect a vector with a Mutex?

2019-07-04 21:01发布

问题:

I am working on designing a C++ server that accepts multiple different interacting clients, and I use vectors to keep track of all of them individually. However, I realized that, because of so many threads running, there's a tiny chance a vector might be read and written to at the same time by two threads. Is there a quick and safe way to add a mutex or something to them so that it will wait until all the reads are done until another function adds to it? Not doing so can mess up the protocol and maybe even crash the server.

I had an idea to create a global variable that would lock all reads to a vector, but I'm not sure if the threads can be told to mutually exclude that variable too (i.e. not change bool to false and check it as true at the same time, rendering the mechanism pointless).

I am using Windows 7 (Visual Studio 2010 Pro). Thanks for any and all advice!

回答1:

Since you are using VS2010, you should use Concurrency::concurrent_vector. But be aware that there are limitations with this class, and is not fully thread-safe. You may use Concurrency::critical_section or Concurrency::reader_writer_lock. Reader-writer lock would give good performance when there are more reads than writes. You may also use Windows native Reader-writer locks, but they are supported only only Windows Vista and higher.



回答2:

The quickest solution is to replace the std::vector with a concurrent_vector. This class mimics std::vector's interface but is thread-safe for concurrent reads and writes.

However, this will make the code non-portable because the concurrent_vector class is part of the Microsoft Parallel Patterns Library and not the C++ standard library. If you want to maintain portability, you'll have to use a Boost.Mutex (since VS2010 doesn't support std::mutex) to gain exclusive access to the vector from each thread. Using a global variable to prevent concurrent access is useless.