Note that there are some explanatory texts on larger screens.

plurals
  1. POProgram using Semaphores runs fine on Linux...unexpected results on Mac osX
    primarykey
    data
    text
    <p>I wrote a simple program solving the Readers-Writers problem using semaphores. It runs perfectly on Linux os, but when I run it on my Mac osX I get unexpected results and I can't figure out why. </p> <p>My Program:</p> <pre><code>#include &lt;semaphore.h&gt; #include &lt;sys/types.h&gt; #include &lt;stdio.h&gt; #include &lt;pthread.h&gt; #include &lt;unistd.h&gt; void* function1(void* val); void* function2(void* val); // shared values volatile int X; volatile int Y; // declare semaphores sem_t s1; sem_t s2; main() { void* status; pthread_t thread1; pthread_t thread2; srand(time(NULL)); // initialize semaphores to zero sem_init(&amp;s1, 0, 0); sem_init(&amp;s2, 0, 0); pthread_create(&amp;thread1, NULL, function1, NULL); pthread_create(&amp;thread2, NULL, function2, NULL); pthread_join(thread1, &amp;status); pthread_join(thread2, &amp;status); sem_destroy(&amp;s1); sem_destroy(&amp;s2); } void* function1(void* val) { while(1) { X = rand()%1000; // write printf("After thread ID A writes to X, X = %d\n", X); sem_post(&amp;s1); // signal sem_wait(&amp;s2); // wait printf("After thread ID A reads from Y, Y = %d\n", Y); // read sleep(3); } } void* function2(void* val) { while(1) { sem_wait(&amp;s1); // wait printf("After thread ID B reads from X, X = %d\n", X); // read Y = rand()%1000; // write printf("After thread ID B write to Y, Y = %d\n", Y); sem_post(&amp;s2); // signal sleep(3); } } </code></pre> <p>The output I receive on Linux (what it's supposed to look like): </p> <pre><code>After thread ID A writes to X, X = 100 After thread ID B reads from X, X = 100 After thread ID B write to Y, Y = 234 After thread ID A reads from Y, Y = 234 ... </code></pre> <p>The output on Mac osX (unexpected):</p> <pre><code>After thread ID A writes to X, X = 253 After thread ID A reads from Y, Y = 0 After thread ID B reads from X, X = 253 After thread ID B write to Y, Y = 728 ... </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    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