The previous STL container deletion operation continued, and STL was easy to use, as well as automatic memory management. Combined with appropriate generic algorithms, the programming efficiency was greatly improved, as a result, we use our programs in an "unscrupulous" manner. However, as long as you have an "unscrupulous" attitude, you will end up taking a detour, such as the thread security issue. First, we will carry it out from memory STL.
Thread Security
Multiple readers are secure. Multithreading may read the content of a container at the same time, which will be correctly executed. Of course, no writer can operate on this container during reading.
It is safe for multiple writers of different containers. Multiple Threads can write different containers at the same time.
Thread insecurity
When performing multi-threaded read/write operations on the same container.
Lock the container during each call to the container's member function.
Lock the container within the lifetime of the iterator returned by each container, for example, by calling begin or end.
Lock the container during execution of each algorithm called on the container.
Have you seen the risk? It is common to operate STL with multiple threads in projects. A typical example is to use STL as the producer-queue of the consumer model or other shared queues, in this way, we must encapsulate container operations to address thread security issues. This is my own encapsulation class threadSafe_container.h. In addition, the book introduces us to a more general encapsulation method. You can refer to the implementation for your reference.
Template <typename Container> // obtain and release the container's mutex class Lock {// The template core of the class; public: // ignores a lot of details Lock (const Containers Container ): c (container) {getMutexFor (c); // obtain the mutex In the constructor }~ Lock () {releaseMutexFor (c); // release it in the Destructor} private: const Container & c ;};
This article from "forever friends" blog, please be sure to keep this source http://yaocoder.blog.51cto.com/2668309/1208465