简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM