Windows Vista and the updated Windows client system, Windows Server 2008 and the updated Windows Server system, added read-write lock API functions, and we no longer have to write read-write locks manually.
To use a read-write lock, of course, include the Windows header file and define a variable of type srwlock (struct):
SRWLOCK Lock;
A variable of type Srwlock cannot be assigned manually, cannot take the value of the field in it, and cannot copy the memory it occupies with a function such as memcpy, and all its operations (initialization, read lock, write lock, etc.) can only be carried out by the relevant function.
The function that initializes the read-write lock is Initializesrwlock, using the following:
Initializesrwlock (&lock);
The parameter type is srwlock*, and the address of the lock you just defined is passed in the past.
The function that is locked for the read operation is acquiresrwlockshared:
Acquiresrwlockshared (&Lock;
The function to unlock for the read operation is releasesrwlockshared:
Releasesrwlockshared (&lock)
The function that is locked for the write operation is acquiresrwlockexclusive:
Acquiresrwlockexclusive (&lock);
The function that is locked for the write operation is releasesrwlockexclusive:
Releasesrwlockexclusive (&lock);
Read-write locks do not need to be deleted manually.
For convenience, I usually encapsulate the read-write lock and its related functions into a class, thus achieving the "out of the box" effect.
Header file srw.h//required://#include <windows.h>class Rwmutex{public:rwmutex (); ~rwmutex () = default; void Rlock (); void Runlock (); void Lock (); void Unlock ();p rivate:srwlock Lock_;private:rwmutex (const rwmutex&) = delete; void operator= (const rwmutex&) = delete;};
Overloaded assignment notation, which returns void instead of Rwmutex&, which is actually more reasonable.
Source file Srw.cpprwmutex::rwmutex () {:: Initializesrwlock (&lock_);} void Rwmutex::rlock () {:: Acquiresrwlockshared (&lock_);} void Rwmutex::runlock () {:: Releasesrwlockshared (&lock_);} void Rwmutex::lock () {:: Acquiresrwlockexclusive (&lock_);} void Rwmutex::unlock () {:: Releasesrwlockexclusive (&lock_);}
New read-write lock function for Windows Vista