Programming in linux: thread synchronization-rwlock and linuxrwlock
Thread Synchronization-read/write lock (rwlock)
Read/write lock
Read/write locks are the details of mutex: Apparently, synchronization is required only when global capital is written; no locks are required when global capital is read.
Related functions
Pthread_rwlock_t // read/write lock type pthread_rwlock_init // initialize the lock // destroy the lock pthread_rwlock_rdlock // obtain the read lock pthread_rwlock_wrlock // obtain the write Lock unlock // release the read/write lock
Example
# Include <stdio. h> # include <unistd. h> # include <pthread. h> pthread_rwlock_t rwlock; int counter = 0; void * fun_r (void * argv) {while (1) {// since it is a read operation, of course, pthread_rwlock_rdlock (& rwlock); printf ("thread % x read, counter = % d \ n", pthread_self (), counter); pthread_rwlock_unlock (& rwlock ); sleep (1) ;}} void * fun_w (void * argv) {while (1) {// write operation. write operation uses the write lock pthread_rwlock_wrlock (& rwlock); counter ++; printf ("thread % x write, counter = % d \ n", pthread_self (), counter); pthread_rwlock_unlock (& rwlock); sleep (1 );}} int main (void) {pthread_rwlock_init (& rwlock, NULL); pthread_t tid [5]; int I; // enable two threads to read for (I = 0; I <2; I ++) {pthread_create (& tid [I], NULL, fun_r, NULL);} // enable three threads to write for (I = 2; I <5; I ++) {pthread_create (& tid [I], NULL, fun_w, NULL) ;}for (I = 0; I <5; I ++) {pthread_join (tid [I], NULL);} pthread_rwlock_destroy (& rwlock); return 0 ;}
CCPP Blog directory
Copyright Disclaimer: This article is an original article by the blogger. For more information, see the source.