1

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.

4

2 に答える 2

1

このように記述されたコードは正しいように見えますが (論理的には)、実際の環境を使用すると正しく動作しません。修正はvolatileキーワードになりますが、理由は少し複雑です。これも、このキーワードの動作のためです。すべての言語/コンパイラを変更します。ここに正解があります

于 2013-06-26T10:44:20.467 に答える