Read and write locks for multithreaded programming

Source: Internet
Author: User

 

In the "Multithreaded programming Linux environment of multi-threaded (ii)" article mentioned in the Linux environment of the multi-threaded synchronization mechanism of one of the read and write lock. This article details the concept and principle of read-write lock.

First, what is a read-write lock

A read-write lock (also known as a shared-exclusive lock) is actually a special spin lock that divides visitors to shared resources into readers and readers, who only read access to shared resources and write to shared resources. This lock improves concurrency relative to spin locks because it allows multiple readers to access shared resources at the same time in a multiprocessor system, with the maximum possible number of readers being the actual number of logical CPUs. The writer is exclusive, and a read-write lock can only have one writer or multiple readers (related to the number of CPUs), but not both the reader and the writer.

If a read-write lock is not currently available to the reader and is not written, then the writer can immediately acquire a read-write lock, otherwise it must "spin" there until there is no writer or reader. If the read-write lock is not written, the reader can immediately obtain the read-write lock, otherwise the reader must "spin" there until the writer releases the read-write lock. A read-write lock is suitable for occasions when the data structure is read more frequently than written.

Implementation methods in two or one Linux environments

The following uses the mutex and condition provided by pthread.h to implement a read-write lock:

#include <pthread.h>structRwlock {pthread_mutex_tLock;    pthread_cond_t read, write; Unsigned readers, writers, read_waiters, Write_waiters;};void Reader_lock (struct Rwlock *Self) {Pthread_mutex_lock (&self->Lock);if (self->writers | | self->Write_waiters) {self->read_waiters++;Do pthread_cond_wait (&self->read, &self->Lock);while (Self->writers | | self->Write_waiters); self->read_waiters--; } self->readers++; Pthread_mutex_unlock (&self->Lock);}void Reader_unlock (struct Rwlock *Self) {Pthread_mutex_lock (&self->Lock); self->readers--;if (self->write_waiters) pthread_cond_signal (&self->Write); Pthread_mutex_unlock (&self->Lock);}void Writer_lock (struct Rwlock *Self) {Pthread_mutex_lock (&self->Lock);if (self->readers | | self->Writers) {self->write_waiters++;Do pthread_cond_wait (&self->write, &self->Lock);while (Self->readers | | self->Writers); self->write_waiters--; } self->writers =1; Pthread_mutex_unlock (&self->Lock);}void Writer_unlock (struct Rwlock *Self) {Pthread_mutex_lock (&self->Lock); Self->writers =0;if (self->write_waiters) pthread_cond_signal (&self->Write);Else if (self->read_waiters) pthread_cond_broadcast (&self->read); Pthread_mutex_unlock ( &self->lock);} void Rwlock_init (struct rwlock * self) {self->readers = Self->writers = Self->read_waiters = SELF-&G T;write_waiters = 0; Pthread_mutex_init (&self->lock, NULL); Pthread_cond_init (&self- >read, NULL); Pthread_cond_init (&self->Write, NULL);}             

This implementation can not increase the number of read locks in case there is a write lock, but the number of read waits is accumulated.

Three or one ways to implement Windows environments

The implementation in the Windows environment is similar, refer to the following example:

typedefstruct_rwlock {IntCountIntState HANDLE Hread; HANDLE Hwrite;} RWLock; typedefEnum/*Enumerate read and write states*/{State_empty =0, State_read, state_write}; rwlock*Create_read_write_lock (HANDLE hread, HANDLE hwrite) {rwlock* Prwlock =NULL; ASSERT (NULL! = Hread && NULL! =Hwrite); Prwlock = (rwlock*) malloc (sizeof(RWLock)); Prwlock->hread =Hread; Prwlock->hwrite =Hwrite; Prwlock->count =0; Prwlock->state =State_empty;ReturnPrwlock;}void Read_lock (rwlock*Prwlock) {assert (NULL! =Prwlock); WaitForSingleObject (prwlock->Hread, INFINITE); Prwlock->count + +;If1 = = Prwlock->Count) {WaitForSingleObject (prwlock->Hwrite, INFINITE); Prwlock->state =State_read; } ReleaseMutex (prwlock->Hread);}void Write_lock (rwlock*Prwlock) {assert (NULL! =Prwlock); WaitForSingleObject (prwlock->Hwrite, INFINITE); Prwlock->state =State_write;}void Read_write_unlock (rwlock*Prwlock) {assert (NULL! = Prwlock); if (State_read = Prwlock->state) { WaitForSingleObject (Prwlock->hread, INFINITE); Prwlock->count--if (0 = = prwlock-> count) {prwlock->state = State_empty; ReleaseMutex (Prwlock->hwrite);} ReleaseMutex (Prwlock->hread);} else{prwlock->state =  State_empty; ReleaseMutex (Prwlock->hwrite);} return;}        

The implementation in the Windows environment is much simpler, but once the write operation in this way acquires a lock, it is only possible to wait for all read operations to finish. If there is always a read operation, then the write operation will be waiting.

Iv. Experience Summary of the use of reading and writing locks

(1) The advantage of reading and writing locks is to maximize efficiency only when reading and writing less, and long running time of code segment;
(2) Any modification of the public data must be done in the lock;
(3) Read-write lock has its own application site, it is very important to choose the appropriate application environment;
(4) Writing a read-write lock is error-prone and requires more practice;
(5) Read lock and write lock must be used separately, otherwise not reach the effect.

Read and write locks for multithreaded programming

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.