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?
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.
pthread_join() — Wait for a thread to end.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With