When writing multithreads, it's very common to have one. That is, there are few opportunities for public data modification. Compared with rewriting, their chances of reading are much higher. Generally speaking, the process of reading is often accompanied by the operation of searching, which takes a long time. Adding a lock to this code segment will greatly reduce the efficiency of our program. Is there a way to deal with the situation of more reading and less writing?
Yes, that's the read-write lock.
(1) first, let's define the basic data structure.
At the same time, to determine whether the current lock is in read or write state, we need to define an enumerator,
(2) initialize data structure
(3) acquire read lock
(4) acquire write lock
(5) release the read-write lock
Article summary:
(1) the advantage of read-write lock can be maximized only when there are two conditions: more read and less write, and long code segment running time;
(2) any modification of public data must be completed in the lock;
(3) the read-write lock has its own application place, so it is very important to choose a suitable application environment;
(4) it's easy to make mistakes in writing and reading locks. Friends should practice more;
(5) the read lock and the write lock must be used separately, otherwise the effect will not be achieved.