Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 619
Pontomedon Avatar asked Jan 09 '13 11:01

Pontomedon


People also ask

Is multi threading possible in C?

C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C program using POSIX.

What is the code if main thread should wait until all other threads are finished in C?

pthread_join() — Wait for a thread to end.

What is pthread_create in C?

DESCRIPTION. The pthread_create() function is used to create a new thread, with attributes specified by attr, within a process. If attr is NULL, the default attributes are used. If the attributes specified by attr are modified later, the thread's attributes are not affected.

Is pthreads faster than OpenMP?

The results shows that OpenMP does perform better than Pthreads in Matrix Multiplication and Mandelbrot set calculation but not on Quick Sort because OpenMP has problem with recursion and Pthreads does not.


1 Answers

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.

like image 198
bobah Avatar answered Oct 11 '22 04:10

bobah