I got this question in a job interview and for the life of me I couldn't find the answer (and they don't tell you the answer at the end since it's a written test):
int thread2_finished = 0;
void t1() {
printf("t1 is running\n");
while (!thread2_finished) { usleep(50); }
printf("t2 is doing stuff\n");
}
void t2() {
printf("t2 is running\n");
sleep(5);
printf("t2 woke up\n");
thread2_finished = 1;
printf("t2 finished\n");
}
What we know is that most of the times it works - but sometimes thread1 never exists (doesn't print the last message) while thread2 does print all his messages - How is that possible?
I'm guessing i'm missing something basic here but the only thing I could think about it that the problem is with the cache - like T1 loads the value (0) and cache it, then immediately T2 changes the value to 1, but for some odd reason T1 will keep using the old cached value but that seems weird to me.