Consider the following C code that creates and joins with two
threads. Assuming that the threads are scheduled completely before the
parent process (i.e., have a higher priority), what will be the output
from running this program? Be careful! There is a significant trick!
int a = 0;
void *print_fn(void *ptr)
{
int tid = *(int *)ptr;
int b = 0;
a++; b++;
printf("id: %d a: %d b: %d\n", tid, a, b);
while (1); // Spin-wait here forever
}
int main()
{
pthread_t t1, t2;
int tid1 = 1;
int tid2 = 2;
int ret1, ret2;
a++;
printf("Parent says a: %d\n", a);
ret1 = pthread_create(&t1, NULL, print_fn, (void *)&tid1);
ret2 = pthread_create(&t2, NULL, print_fn, (void *)&tid2);
if (ret1 || ret2) {
fprintf(stderr, "ERROR: pthread_create failed\n");
exit(1);
}
if (pthread_join(t1, NULL)) {
perror("join of t1");
exit(1);
}
if (pthread_join(t2, NULL)) {
perror("join of t2");
exit(1);
}
printf("Thread 1 and 2 complete\n");
}