Reputation: 947
Consider the following situation:
I have an object foo that is used by multiple threads, that may or may not repeatedly call a method bar() on foo.
It is perfectly fine (and desired) that bar() is executed multiple times in parallel, as it never changes the state of foo.
The problem arises when i need to change the state of foo from the outside (from another thread, not from one of the "worker" threads) - how can i lock foo in a way so that the calling thread blocks until the last worker thread is done with bar() and all worker threads will block at bar() until i release foo again?
Obviously i cannot just use a mutex that is remains locked during execution of bar(), because then i won't have concurrency there.
Any ideas? Or is there a better design for those types of problems?
Upvotes: 6
Views: 757
Reputation: 18864
I am not sure how you are going to achieve, that none of workers are using foo to let writer update it, but if it is not of a concern then just use a read/write mutex (workers to obtain read lock, writer to obtain write lock).
It is worth mentioning though, that you might want to consider making foo Copy-on-Write. This way you will make synchronization overhead close to zero. You can use shared_ptr atomically to achieve that.
Upvotes: 4