c - pthread_rwlock_rdlock resulting in number of readers going as negative -
when can scenario happen?
one of threads stuck on write , other keeps calling read_lock resulting in negative readers increase. write attempts done same thread , reads thread.
the following lock definitions ->
typedef sp_rwlock_t pthread_rwlock_t; int sp_rwlock_rlock(sp_rwlock_t *lock) { int status; if (lock->__data.__nr_readers > 1) { syslog(log_err,"%s:wierd readers :%d\n",__func__, lock->__data.__nr_readers); } if (lock) { if ((status = pthread_rwlock_rdlock(lock)) == 0) { return sp_ok; } else { syslog(log_err,"error in func: %s errno %x\n",__func__, status); return sp_error; } } /* if lock */ return sp_invalid_arg; } int sp_rwlock_wlock(sp_rwlock_t *lock) { if (lock->__data.__nr_readers > 0) { syslog(log_err,"%s:wierd readers\n",__func__); } if (lock) { if (pthread_rwlock_wrlock(lock) == 0) { return sp_ok; } else { syslog(log_err,"error in func: %s errno %x\n",__func__, errno); return sp_error; } } /* if lock */ return sp_invalid_arg; }
following logs seen ->
sp_rwlock_rlock:wierd readers :-1
error in func: sp_rwlock_rlock errno b
sp_rwlock_rlock:wierd readers :-3
sp_rwlock_rlock:wierd readers :-4
sp_rwlock_wlock:wierd readers
sp_rwlock_rlock:wierd readers :-5
sp_rwlock_rlock:wierd readers :-6
sp_rwlock_rlock:wierd readers :-7
__nr_readers
unsigned int
- @ least in version of glibc - , printing %d
signed ints. use %u
format correctly.
the __nr_readers
being decremented beyond 0 means you're unlocking lock more times you've locked - undefined behaviour.
(you shouldn't poking around in lock internals anyway - reading __nr_readers
should have glibc low-level-lock protects rwlock internals held.)
if have 1 thread reading, there's no point in using rwlock anyway - might using plain mutex. benefit of rwlock can have multiple readers accessing data simultaneously.
Comments
Post a Comment