I have a map as member variable and multiple threads that access the map (read and write access). Now I have to ensure that only ONE thread have access to the map. But how do I dot that? What is the best solution for that?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Difference between Thread#run and Thread#wakeup?
- Selecting only the first few characters in a strin
- Java/Spring MVC: provide request context to child
- What exactly do pointers store? (C++)
Boost contains some nice lock implementations for shared access. Have a look at the documentation.
In your case you probably need a read-write lock because a mutual exclusion lock is probably overkill if you have a lot of reads and very few writes.
You need to synchronize access to your map, for example by using a POSIX mutex. The link has some simple to follow examples of how you use mutual exclusion variables.
Actually, the premise that only a single thread should access to the
map
at a given time is slightly off.Concurrent reads are okay, what you want to avoid is having a thread modifying the map while others are reading it.
Depending on the level of granularity you need, you might consider a reader/writer lock, which will let several reads proceed in parallel.
The exact usage was demonstrated here using Boost:
After that, it is just a matter of conveniently wrapping the map access. For example, you could use a generic proxy structure:
And you can use them as:
Beware of iterators though, they can only be safely manipulated while the mutex is hold by the current thread.
Also, I recommend that you keep the map under tight control, fitting it into the smallest object that make sense, and provide only those operations you need. The least methods have access to the map, the less likely you are to miss one access point.
If you have a recent compiler, you can use
std::mutex
(which is based on the boost implementation). This is part of C++11, so it isn't implemented everywhere. gcc-4.6 works fairly well though. The underlying implementation is POSIX threads in linux and Windows threads in Windows.