[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
In mutually exclusive data access, there is a situation where multiple reads and writes are less. For such a situation, we also propose a read/write Lock solution. However, this lock has some defects. What are the defects? That is, This write lock can only be written after all the read locks are completed. Otherwise, the write lock needs to wait.
So, is there any way to make write operations faster? That is the sequential lock.
[CPP] View plaincopy
- Typedef Struct_ Sequence_lock
- {
- UnsignedIntSequence;
- HandleHlock;
- } Sequence_lock;
With such a data structure. So how can I start reading locks,
[CPP] View plaincopy
-
- UnsignedIntGet_lock_begin (sequence_lock * hseqlock)
-
- {
-
- Assert (null! = Hseqlock );
-
-
- ReturnHseqlock-> sequence;
-
- }
-
- IntGet_lock_retry (sequence_lock * hseqlock, unsignedIntValue)
-
- {
-
- UnsignedIntNew_value;
-
- Assert (null! = Hseqlock );
-
-
- New_value = hseqlock-> sequence;
-
- Return(New_value & 0x1) | (new_value ^ value );
- }
The write lock also needs to be modified,
[CPP] View plaincopy
-
- VoidGet_write_lock (sequence_lock * hseqlock)
-
- {
-
- Assert (null! = Hseqlock );
-
-
- Waitforsingleobject (hseqlock-> hlock );
-
- Hseqlock-> sequence ++;
-
- }
-
- VoidRelease_write_lock (sequence_lock * hseqlock)
-
- {
-
- Assert (null! = Hseqlock );
-
-
- Hseqlock-> sequence ++;
-
- Releasemutex (hseqlock-> hlock );
-
- }
If the application is used, it is not difficult,
[CPP] View plaincopy
-
- VoidRead_process (sequence_lock * hseqlock)
-
- {
- UnsignedIntSequence;
-
-
- Do{
-
- Sequence = get_lock_begin (hseqlock );
-
- /* Read operation */
-
- }While(Get_lock_retry (hseqlock, sequence ));
-
- }
-
- VoidWrite_process (sequencce_lock * hseqlock)
-
- {
-
- Get_write_lock (hseqlock );
-
- /* Write operation */
-
- Release_write_lock (hseqlock );
-
- }
Summary:
(1) There are two conditions for exit of the read lock: either the write operation is in progress or no write lock.
(2) The write locks must be mutually exclusive.
(3) The data of mutex operations cannot be pointers. Otherwise, exceptions may occur during access because it is possible to write and read simultaneously.
(4) The sequential lock cannot replace the read/write lock, because the read/write lock can ensure all data operations, but the sequential lock cannot.