In a video player program, this architecture is often used:
A thread that is responsible for reading the file, is responsible for reading the data from the media file and putting the packet in a packet queue, and another thread is fetching the packet from the packet queue and decoding it, and then handing it to the thread responsible for displaying the image. As a result, multiple threads are formed to share a queue, a write, and a number of read-only non-writable cases.
In many cases, we will encounter a write thread (responsible for writing data), multiple read threads (responsible for reading data). In such cases, of course, locks can be used to ensure that each thread's access to the shared data is exclusive. But such a practice is inefficient in this case, because it causes a read thread to read the data while the other read thread can only wait.
Given that a thread's reading of shared data does not interfere with the reading of other threads, we need the "read and write lock" thing.
Set M as a read-write lock, when thread a writes a lock on M, the other thread cannot read or write the lock on M, until a unlocks the write lock of M, and when a thread B reads the lock on M, the other thread can read the lock on M and cannot write the lock on M until B unlocks the read lock to M.
First, initialize
Before you use a read-write lock, define a variable of type Srwlock:
SRWLOCK RWM;
Like the critical section, RWM cannot modify the read in the code, and all operations on it must be done through the relevant functions .
Initialize the read-write lock with the Initializesrwlock function,
Initializesrwlock (&RWM);
Second, lock and unlock
Read lock acquiresrwlockshared (&RWM);//Interpretation Lock releasesrwlockshared (&RWM);//write Lock acquiresrwlockexclusive (&RWM) ;//write Lock releasesrwlockexclusive (&RWM);
Third, the destruction
Read-write locks do not need to be destroyed manually.
Iv. encapsulation into class
For ease of use, I generally encapsulate it into a class to achieve out-of-the-box effects.
Header file:
Class Rwmutex{public:rwmutex (); ~rwmutex () = default; void Rlock (); Read lock void Runlock (); Read lock void Lock (); Write lock void Unlock (); Write lock Private:srwlock Lock_;private:rwmutex (const rwmutex&) = delete; void operator= (const rwmutex&) = delete;};
The corresponding source file:
Rwmutex::rwmutex () {:: Initializesrwlock (&lock_);} void Rwmutex::rlock () {:: Acquiresrwlockshared (&lock_);} void Rwmutex::runlock () {:: Releasesrwlockshared (&lock_);} void Rwmutex::lock () {:: Acquiresrwlockexclusive (&lock_);} void Rwmutex::unlock () {:: Releasesrwlockexclusive (&lock_);}
Windows thread Synchronization "4" read-write Lock (Rwmutex)