Linux system Programming: Thread synchronization-read-write lock (Rwlock)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.