Sharing pthread data and child processes in C

my question is somewhat conceptual how the data of the parent process is shared with the child process created by the fork() call, or with the thread created by pthread_create()

for example, are global variables directly passed to the child process, and if so, does the modification of this variable made by its child process in its parent process?

I appreciate partial and complete answers in advance, if I am missing an existing resource, sorry, I did a google search but could not find good results.

thanks again for your time and answers

+4
source share
3 answers

The semantics of fork () and pthread_create () are slightly different.

fork () will create a new process where global variables will be split between parent and child. Most OS implementations will use copy-on-write semantics, which means that both the parent and child processes will use the same pages of physical memory for all global variables until one of the processes tries to edit the physical memory, after which a copy of this page, so now each process gets its own copy and does not see another process, so the processes are isolated.

pthread_create (), on the other hand, creates a new thread within a single process. The new thread will have a separate stack space from other working threads of the same process, however global variables and empty space are shared between all threads of the same process. This is why you often need a mutex to coordinate access to a common piece of memory between multiple threads of the same process.

TL DR version: with fork () you do not see the changes of another guy; using pthread_create ().

+5
source

Fork creates an almost exact copy of the calling process, including memory and file descriptors. Global variables are copied along with everything else, but they are in no way associated with the parent process. Since file descriptors are also copied, the parent and child can interact through them (provided that they are correctly configured, usually through a pipe or socket stick).

+2
source

There is a big difference between processes created by fork and between threads created using pthread_create . Processes do not use global variables and must interact through channels, sockets, or other tools provided by the OS. A good solution is MPI, a message passing library for inter-process communication.

The streams are very different. A thread created using pthread_create shares all global variables with its caller. Moreover, the caller can pass an arbitrary structure to the stream, and this structure will also be shared. This means that when programming with threads, you need to be very careful - such amounts of sharing are dangerous and error prone. The pthread API provides mutexes and conditions for reliable synchronization between threads (although this still requires practical implementation and experience).

+1
source

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


All Articles