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.
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.