-2

When I run the following program, the output is 5.
Why 5? Why not 8?

void *doit(void *vargp) {
    int i = 3;
    int *ptr = (int*)vargp;
    (*ptr)++;
}
int main() {
    int i = 0;
    pthread_t tid;
    pthread_create(&tid, NULL, doit, (void*)&i);
    pthread_join(tid,NULL);
    i = i + 4;
    printf("%d",i);
}
Pang
  • 9,564
  • 146
  • 81
  • 122
sadsadas
  • 1
  • 1
  • 2
    The line `int i = 3;` doesn't do anything. That line assigns a value to a local variable, which is never used. – user3386109 May 08 '17 at 04:49
  • 2
    The thread doesn't add anything meaningful, so your question can get summarized as "why does the following code print 5?" `int i=0; i++; i=i+4;`. it does because 1+4=5. – Lundin May 08 '17 at 08:11

3 Answers3

6

In doit, the value of i is incremented from 0 to 1 at statement

(*ptr)++

After the thread is done you increment it by 4

i = i + 4;

so the value is 5

Pras
  • 4,047
  • 10
  • 20
2

In doit() you have incremented the i by 1 ( of main function passed by referance ) and after the thread join you added 4 to it.

To get 8 you might have added 3 to the passed parameter instead of just incrementing it, in doit().

S Jayesh
  • 191
  • 1
  • 4
  • 19
1
  • In function doit int i=3; is a local variable for doit function it is not related to the i which you have declared in main. So making addition there has no effect on i in main function. You can remove it.

    • Next, the (*ptr)++ increments pointer vargp pointing to i declared in main function by 1. So, there i becomes 1 and next you are adding4. SO the result is 5. If you want eight the increment (*ptr) for 3 times or in doit assign vargp variable to 2, the do (*ptr)++ only once and see the output.
ams
  • 315
  • 4
  • 17