Pthreads / wait (& status)

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.

+4
source share
3 answers

Answers to your questions:

  • The value will be 0 in the parent process, since when fork parent's address space is duplicated (along with the value variable) in the child process. Therefore, although value changes in the child, this change is not reflected in the parent, since they are different variables.

  • Since no synchronization exists, there is no way to find out in what order the value variable is changed by three child threads. In particular, each thread has a local variable temp with a different value, which is then copied to the global variable value , but there is no way to find out in which order the threads will overwrite value with temp here: value = temp; . Therefore, its meaning may vary depending on the performance.

+3
source

Because when you use fork, you get a completely new process with its own memory, which means that changes to a variable in one process will not be displayed in another. On the other hand, threads share their memory, which means that changes in variables in a multi-threaded program are displayed in all threads.

0
source

The value is incremented by the child process, so the parent process will display its value as 0.

 if(fork_id == 0){ ...... ...... } 

performed by the child that spawned the threads.

And the child process has another copy of memory. therefore, an increasing value in the child file does not mean the same for the parent.

And threads have access to global values.

0
source

Source: https://habr.com/ru/post/1413933/


All Articles