Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>All, I have solved this problem very, very easily. I am embarrassed for not catching this sooner, but I took a break from this code for a while. The solution is so trivial. All that was needed was an extra condition variable that the generator waits on until the monitor is finished. Here is the code.</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; volatile 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, gen; 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); //signal monitor pthread_cond_wait(&amp;gen, &amp;mutex); //wait for monitor to finish *Solution* 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 var for monitor pthread_cond_init(&amp;gen, NULL); //initialize condition var for generator pthread_create(&amp;generator, NULL, generator_func, NULL); //create thread //monitor pthread_mutex_lock(&amp;mutex); while(done != 1 || is_square == 1){ 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_cond_signal(&amp;gen); //start generator back up *Solution* } 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>
    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.
 

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