Thread synchronization-read-write lock (Rwlock)
read/write lock
A read-write lock is a refinement of the mutex: it is clear that synchronization is required only when a global asset is written, and no lock is required when reading a global asset.
related Functions
pthread_rwlock_t //read/write lock type pthread_rwlock_init//Initialize Pthread_rwlock_destroy// destroy lock Pthread_rwlock_rdlock Get read lock Pthread_rwlock_wrlock //Get write lock Pthread_rwlock_tryrdlockpthread_rwlock_trywrlockpthread_rwlock_unlock //release 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, you can of course not lock Pthread_rwlock_rdlock (&rwlock);p rintf ("Thread%x read, Counter=%d\n ", pthread_self (), counter);p Thread_rwlock_unlock (&rwlock); sleep (1);}} void *fun_w (void *argv) {while (1) {//write operation, write operation using write lock Pthread_rwlock_wrlock (&rwlock); counter++;p rintf ("Thread%x write , counter=%d\n ", pthread_self (), counter);p Thread_rwlock_unlock (&rwlock); sleep (1);}} int main (void) {Pthread_rwlock_init (&rwlock, NULL);p thread_t tid[5];int i;//open 2 threads read for (i = 0; i < 2; i++) {Pthread_ Create (&tid[i], NULL, fun_r, NULL);} Open 3 Threads 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 NOTICE: This article is for bloggers original articles, reproduced, please indicate the source.
Linux system Programming: Thread synchronization-read-write lock (Rwlock)