I read a book that gives the following example:
int value=0 int thread_func(int id) { int temp; temp=value+id; printf("Thread%d value: %d", id, temp); value=temp; } int main() { int fork_id, status, i; pthread_t tids[3]; fork_id=fork(); if (fork_id == 0) { for (i=1; iβ€3; i++) pthread_create(&tids[i-1], NULL, thread_func, i); for (i=0; iβ€2; i++) pthread_join(tids+i, &status); printf("Second process value: %d", value); } else { wait(&status); printf("First process value: %d", value) }
I donβt understand two main things: When I read, the only value that the line in printf("First process value: %d", value)
is 0. But why? wait (& status) waits for the child process to complete. Otherwise, it will stop only after all connections are completed. value when the value is 6.
Secondly, in the line printf("Second process value: %d", value);
vaul can be from 1 to 6. This is also strange because we have a connection command.
source share