Subj : Re: Concurrent reads and sequential writes To : comp.programming.threads From : Joe Seigh Date : Tue Jul 26 2005 12:27 pm kozlovsky@kozlovsky-c4.sipo.gess.ethz.ch wrote: > Hello, > > I am writing a spider application on Linux, C++, STL, pthreads. > The application has a cache that contains (word, handle) pairs. > The Cache class has method "get", that, given a word, returns its > handle (if found in the cache), and method "add", that adds a > new pair to the cache. About 95% of cache access are get's. > > At present, the cache is synchronized with a single mutex, so > only a single thread can access the cache at any given time. > I would like to change synchronization in such a way that any > number of threads can call "get" at the same time, while "add" > must remain exclusive, i.e. only one thread can execute "add" > after blocking threads from starting new "get" and waiting > till threads currently executing "get" are all finished. > > I cannot figure out how to do it with mutexes, although this > seems to be a quite common situation, is it? Should I use > semaphores? Or may be sig_atomic_t? Why should I try to > reinvent the bycicle? Perhaps there is a known simple > solution to my problem. Please, help. > It's called the reader/writer problem. An rwlock might suffice but it's not clear how you are handling the gets. Is all access via the returned handle guarded by the mutex or are you doing something bad? If access via the handles is not of relatively short duration then you may want to look at reader/writer solution using reference counting or someother GC based solution. In C++ you can use shared_ptr making the get method a factory method that returns a shared_ptr, bearing in mind that shared_ptr is only thread-safe as int, i.e. you need a lock to copy a shared_ptr safely. -- Joe Seigh When you get lemons, you make lemonade. When you get hardware, you make software. .