Programming in linux: thread synchronization-rwlock and linuxrwlock

Source: Internet
Author: User

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.

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.