Wait for multiple threads (Posix threads, C ++)

Consider the following situation:

I have a foo object that is used by multiple threads that may or may not repeatedly call the method bar () on foo.

It is perfectly fine (and desirable) that bar () is executed several times in parallel, since 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, and not from one of the "worker" threads) - how can I block foo so that the calling thread blocks until the last worker thread is executed using bar (), and will all worker threads be blocked in bar () until I return foo again?

Obviously, I can't just use a mutex that stays locked while bar () is running, because then I will not have concurrency.

Any ideas? Or is there a better design for these problems?

+6
source share
1 answer

I'm not sure how you are going to achieve that none of the workers use foo to allow the author to update it, but if that doesn’t bother, just use the read / write mutex (workers get the ability to lock read, write to write write lock).

It should be noted that you might want to do foo Copy-on-Write. This way you will put the synchronization overhead to zero. You can use shared_ptr atomically to achieve this.

+4
source

All Articles