Note that there are some explanatory texts on larger screens.

plurals
  1. POProblem with thread synchronization and condition variables in C
    primarykey
    data
    text
    <p>I have three threads, one thread is the main and the other two are worker threads. The first thread, when there is work to be done wakes up one of the two threads. Each thread when awakened perform some computation and while doing this if it finds more work to do can wake up the other working thread or simply decide to do the job by itself (By adding work to a local queue, for example). While the worker threads have work to do, the main thread must wait for the work to be done. I have implemented this with condition variables as follows (the code reported here hides a lot of details, please ask if there's something non understandable):</p> <p>MAIN THREAD (pseudocode):</p> <pre><code>//this function can be called from the main several time. It blocks the main thread till the work is done. void new_work(){ //signaling to worker threads if work is available //Now, the threads have been awakened, it's time to sleep till they have finished. pthread_mutex_lock(&amp;main_lock); while (work &gt; 0) //work is a shared atomic integer, incremented each time there's work to do and decremented when finished executing some work unit pthread_cond_wait(&amp;main_cond); pthread_mutex_unlock(&amp;main_lock); } </code></pre> <p>WORKER THREADS:</p> <pre><code>while (1){ pthread_mutex_lock(&amp;main_lock); if (work == 0) pthread_cond_signal(&amp;main_cond); pthread_mutex_unlock(&amp;main_lock); //code to let the worker thread wait again -- PROBLEM! while (I have work to do, in my queue){ do_work() } } </code></pre> <p>Here is the problem: when a worker thread wakes up the main thread I'm not sure that the worker thread calls a wait to put itself in a waiting state for new work. Even if I implement this wait with another condition variable, it can happen that the main thread is awake, does some work until reaches a point in which he has to wake up the thread that has not called a wait yet... and this can lead to bad results. I've tried several ways to solve this issue but I couldn't find a solution, maybe there is an obvious way to solve it but I'm missing it.</p> <p>Can you provide a scheme to solve this kind of problem? I'm using the C language and I can use whatever synchronization mechanism you think can be suited, like pthreads or posix semaphores.</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload