1

This is a question related to coursework that I got wrong earlier, and I cannot figure out why.

The following code is given:

int i = 0;

void *doit(void *vargp) {
    i = i + 5;
}

int main() { 
    pthread_t tid; 
    ptr = &i;
    pthread_create(&tid, NULL, doit, NULL);
    i = i + 3; 
    pthread_join(tid, NULL); 
    printf("%d",i);
}

The possible outputs are 8, 3, and 5.

My understanding of the code is that the main thread calls pthread_join(), which waits on the doit thread before proceeding, so both operations (i += 5 and i += 3) must be executed before the print statement is reached. So, I don't understand how 3 and 5 are possible outputs.

Am I understanding pthread_join() incorrectly? Or might this be a mistake on the professor's part? I can definitely see how 8 is a possible output value, but I'm not so sure about 3 and 5.

Naldhelaan
  • 390
  • 4
  • 13
  • Actually, the behavior is undefined. *Any* output, including no output at all, is permissible. – EOF May 05 '16 at 17:02
  • Hmm, can you elaborate? – Naldhelaan May 05 '16 at 17:04
  • C11 draft standard n1570: *5.1.2.4 Multi-threaded executions and data races 4 Two expression evaluations conflict if one of them modifies a memory location and the other one reads or modifies the same memory location. 25 The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.* Similar language is used in POSIX, with the difference being that POSIX doesn't have atomics by itself. – EOF May 05 '16 at 17:07

1 Answers1

0

3 is possible if i = i + 3 starts to run first. i + 3 will evaluate to 3. This might be written back to i after all the i = i + 5 statements have been ran.

8 and 5 are yielded similarly.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Right, instruction interweaving! For some reason I assumed all of the operations are atomic. Thanks for pointing that out! – Naldhelaan May 05 '16 at 14:30