A4Treok
A4Treok

Reputation: 17

Semaphore (Mutex) Example, Race Conditions

I'm having some trouble understanding why this code results in a race condition. As I see it, as soon as a thread begins in the foo function, it blocks out the other thread with sem_wait, and then releases the block after it has written to myid. However, I keep getting an output of Thread 2 Thread 2. I don't understand how this can occur, given that the blocks are in place around the write. Can someone help me rationalize this?

Many thanks.

  sem_t s; /* semaphore s */

 void *foo(void *vargp)
 {
     int myid;
     sem_wait(&s);
     myid = *((int *)vargp);
     sem_post(&s);
     printf("Thread %d\n", myid);
}

int main() {
     pthread_t tid[2];
     int i;
     sem_init(&s, 0, 1); 
     for (i = 0; i < 2; i++) 
          pthread_create(&tid[i], 0, foo, &i);
     pthread_join(tid[0], 0);
     pthread_join(tid[1], 0);
}

Upvotes: 0

Views: 344

Answers (1)

zch
zch

Reputation: 15278

Your two worker threads do not have race conditions with each other, but each has race condition with main thread. myid = *((int *)vargp); in worker can occur at the same time as i++ in main thread.

This is read/write conflict and so undefined behavior, but Thread 2 Thread 2 result seems most likely: main thread would increment i to 2 before new threads even start running. pthread_create only creates "ready" thread, it doesn't need to be scheduled to run immediately.

Upvotes: 1

Related Questions