I\'m learning pthread and came across reader writer lock. The scenario is very simple; a global variable being shared by all the threads, reader keeps printing the current v
When a thread acquires a lock, other threads trying to acquire the same lock will be suspended until the first thread releases the lock.
What is happening here is that your reader thread starts, acquires the lock, and enters the for/poll
loop.
The writer thread starts, tries to acquire the lock which was already taken by the reader thread, and remains blocked on pthread_rwlock_wrlock
.
What you actually want to do is to put your lock/unlock
right before and after the code where you access your shared variable.
thread_rwlock_rdlock(p);
newx = ACCESS_ONCE(x);
thread_rwlock_unlock(p);
...
thread_rwlock_wrlock(p);
ACCESS_ONCE(x)++;
thread_rwlock_unlock(p);