using read write lock in pthreads

When sharing resources between multiple threads, it is safe to allow multiple readers to access the resource simultaneous as they would not alter any data but only one writer should be allowed to access the resource at any given time.

The standard mutex, pthread_mutex_t, allows only one process to access the resource irrespective of whether the process is a reader or writer. The behavior even though safe, is not efficient, as the readers are made to wait even though they are not going to modify the data.

To allow multiple readers to access a resource at the same time we can use pthread_rwlock_t in pthreads. The pthread_rwlock_t which is a read,write lock allows multiple readers to access the resource, but allows only one reader at any given time.

The initialization function for this s

Thus we can use the initialization function as

Once the lock is initialized we can lock a resource for writing using the function

Once the write lock is held no other process can access the resource until it is unlocked using

To lock the resource only for reading and not writing we can use the function

Once the lock is held for reading, any number of other processes can access the resource of reading by locking the resource simultaneously. But the lock can not be held for writing, if it is already being held for reading. The lock can be unlocked using

To depict the working of rwlock let us look at the following example in which we create 4 threads, two for writing write_1,write_2, and two for reading,read_1,read_2.

We try to lock the rwlock in the following order

According to the above order we should not be able to get lock in write_1 and write_2 simultaneously but we should be able to get the lock simultaneously for read_1 and read_2.

Save the above code as rw_lock.c

Compile it using the -lpthread flag

From the output we can see that the two writes were executed one after the other. But in case of reads, even though read_1 had not unlocked the rwlock, read_2 was allowed into the critical section and read the file. Thus indicating that multiple readers are allowed but only one writer is allowed into the critical section.

Follow by Email