7. Spinning vs. Yielding
-
Example: Q6,7 main-signal.c
1 #include <stdio.h> 2 3 #include "common_threads.h" 4 5 int done = 0; 6 7 void* worker(void* arg) { 8 printf("this should print first\n"); 9 done = 1; 10 return NULL; 11 } 12 13 int main(int argc, char *argv[]) { 14 pthread_t p; 15 Pthread_create(&p, NULL, worker, NULL); 16 while (done == 0) 17 ; 18 printf("this should print last\n"); 19 return 0; 20 }
valgrind warns about a possible data race, but the warning is spurious and the code is correct.Improve using sched_yield()