concurrency - pthreads locking scheme to allow concurrent reads of a shared data structure -
let's have code both reads , writes data structure. if have multiple threads executing code (and sharing data structure), there arrangement achieve following:
- allow 2 or more concurrent reads, no writes
- disallow 2 or more writes
- disallow 1 or more reads concurrently 1 or more writes
a single mutex locked during read , write achieves goals 2 , 3, fails achieve goal 1. there solution achieves 3 goals?
assume not possible devise scheme different sub-sections of data structure can protected different mutexes.
my clunkly approach is:
have 1 mutex per thread, , each thread locks own mutex when needs read.
have 1 additional 'global' mutex. when thread wants write, first locks global mutex. goes through loop of pthread_mutex_trylock() on of thread-specific mutexes until has locked them all, performs write, unlocks them all. finally, unlocks global mutex.
this approach seems not efficient, however.
thanks in advance,
henry
pthreads includes reader-writer locks have behaviour. initialise them in analagous way mutexes - either statically:
pthread_rwlock_t rwlock = pthread_rwlock_initializer;
or dynamically pthread_rwlock_init()
.
to lock reading (shared) use pthread_rwlock_rdlock()
, , lock writing (exclusive) use pthread_rwlock_wrlock()
. there "trylock" , "timedlock" variations of these.
you can, of course, build such lock pthreads mutex , condition variables. example, implement reader-side lock as:
pthread_mutex_lock(&mutex); readers++; pthread_mutex_unlock(&mutex);
the writer-side lock is:
pthread_mutex_lock(&mutex); while (readers > 0) pthread_cond_wait(&mutex, &cond);
the reader-side unlock is:
pthread_mutex_lock(&mutex); if (--readers == 0) pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex);
and writer-side unlock is:
pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex);
(this interest's sake - better off using built-in reader-writer locks, because can implemented directly using architecture-specific code may more efficient using other pthreads primitives).
note in real implementation want consider case of readers
overflowing.
Comments
Post a Comment