when i link foo.c (see attached) with -lpthread and run it,
i get the following incorrect ouput:
---------------------------------------------------------------
thread 1 created
thread 2 created
main thread waiting ...
thread 1 acquiring read lock
thread 1 read lock acquisition succeeded
thread 2 acquiring read lock
thread 2 read lock acquisition succeeded
thread 1 releasing read lock
thread 1 read lock release succeeded
thread 1 acquiring write lock
thread 1 write lock acquisition succeeded        /**** error ****/
thread 1 releasing write lock
thread 1 write lock release succeeded
thread 1 dying ...
thread 2 releasing read lock
thread 2 read lock release failed
thread 2 acquiring write lock
thread 2 write lock acquisition succeeded
thread 2 releasing write lock
thread 2 write lock release succeeded
thread 2 dying ...
---------------------------------------------------------------
at the marked point, thread 1 should have blocked because thread 2
still holds the read lock.

i think the reason for this is that when thread 1 acquires the read lock,
it is the first reader, so it acquires rwlock->rw_mutex_rw.  however,
when it releases the read lock, it is not the last reader, so it did not
release rwlock->rw_mutex_rw.  so when it tries to acquire the write
lock, it succeeds because the mutex is recursive and thread 1 still
owns it.

i changed the implementation to use a mutex and a conditional
variable (see attached patch), and foo.c gives the following correct
output.
---------------------------------------------------------------
thread 1 created
thread 2 created
main thread waiting ...
thread 1 acquiring read lock
thread 1 read lock acquisition succeeded
thread 2 acquiring read lock
thread 2 read lock acquisition succeeded
thread 1 releasing read lock
thread 1 read lock release succeeded
thread 1 acquiring write lock
thread 2 releasing read lock
thread 1 write lock acquisition succeeded
thread 1 releasing write lock
thread 1 write lock release succeeded
thread 1 dying ...
thread 2 read lock release succeeded
thread 2 acquiring write lock
thread 2 write lock acquisition succeeded
thread 2 releasing write lock
thread 2 write lock release succeeded
thread 2 dying ...
---------------------------------------------------------------


sincerely,
xiaoguang li



Attachment: pth_rwlock.diff
Description: pth_rwlock.diff

Attachment: foo.c
Description: foo.c

Reply via email to