Note that there are some explanatory texts on larger screens.

plurals
  1. POSimple Generator-monitor program with condition variables
    text
    copied!<p>I created a simple program that uses condition variables to create synchronization between two threads. I'm getting a strange output that I cannot seem to find the solution to. </p> <p><strong>What the program does is</strong>, in the generator thread, produces 1000 random integers and checks to see if they are perfect squares. If the number is a perfect square then it signals the monitor thread which prints the square root of the number. </p> <p><strong>The problem</strong> I am having is most likely some sort of race condition, because the monitor simply isn't printing out the square root when the generator signals. </p> <p><strong>The strange part</strong> is that when I debug in gdb b stepping through each time the variable <code>is_square</code> changes, the problem is nonexistent. </p> <p>Any insight would appreciated. I feel it has to do with my mutex or placement of conditions.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; #include &lt;pthread.h&gt; #include &lt;time.h&gt; int square_root; int is_square = 0; int done = 0; int count = 0; //used to count how many perfect squares generator_func finds int count1 = 0; //used to compare how many responses monitor makes to signal pthread_mutex_t mutex; pthread_cond_t mon; void* generator_func(void* args){ srand(time(NULL)); int i, temp, sq; for(i = 0; i&lt;1000; i++){ temp = rand() % 10000; sq = sqrt((double)temp); if((pow(sq,2)) == temp){ pthread_mutex_lock(&amp;mutex); count++; square_root = sq; is_square = 1; fprintf(stderr, "Square root of %d is", temp); pthread_cond_signal(&amp;mon); pthread_mutex_unlock(&amp;mutex); } } pthread_mutex_lock(&amp;mutex); done = 1; is_square = -1; pthread_cond_signal(&amp;mon); pthread_mutex_unlock(&amp;mutex); } main(){ pthread_t generator; //declare thread pthread_mutex_init(&amp;mutex, NULL); //initialize mutex pthread_cond_init(&amp;mon, NULL); //initialize condition variable pthread_create(&amp;generator, NULL, generator_func, NULL); //create thread //monitor while(done != 1){ pthread_mutex_lock(&amp;mutex); while(is_square == 0){ pthread_cond_wait(&amp;mon, &amp;mutex); } if(is_square == 1 &amp;&amp; done != 1){ count1++; fprintf(stderr, " %d\n", square_root); is_square = 0; } pthread_mutex_unlock(&amp;mutex); } pthread_join(generator, NULL); printf("%d %d\n", count, count1); //shows inconsistency between generator and monitor pthread_mutex_destroy(&amp;mutex); pthread_cond_destroy(&amp;mon); } </code></pre>
 

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