I'm noob on this thread issue :\\
I imagine that Write Lock behaves like a while
that waits for the confirmation of a global variable. Like:
/* pthread_rwlock_wrlock */
while (is_blocked) {
/* waiting */
}
is_blocked = true;
(writing code...)
/* pthread_rwlock_unlock */
is_blocked = false;
Is that correct? And how Read Lock works? If it is shared, why use?
information:
pthread_rwlock_rdlock() – get a shared read lock
pthread_rwlock_wrlock() – get an exclusive write lock
The purpose of a read lock, is to block writers.
Neither has a trivial implementation, the one you suggested for
example have a race-condition, and would sometimes fail.
When you read a protected resource you don't want it to change while you read it.
A read locks blocks write locks!
That means that while you have a read lock, someone trying to get a write lock will have to wait until you, and anyone else who has a read lock, are finished reading. Since reading doesn't change the resource it is OK that several readers read concurrently.
Note that the definition of a reading operation in this context is any operation that doesn't change the state of the protected resource. So for the purposes of read/write locks, if the protected resource is a stream (like stdin
or a socket), reading from it will change its state and should require a write lock.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.