Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread and child process data sharing in C

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

for example, are global variables directly passed into child process and if so, does modification on that variable made by child process effect value of it in parent process?

i appreciate partial and complete answers in advance, if i'm missing any existing resource, i'm sorry, i've done some search on google but couldn't find good results

thanks again for your time and answers

like image 440
besamelsosu Avatar asked Feb 27 '23 06:02

besamelsosu


1 Answers

The semantics of fork() and pthread_create() are a little different.

fork() will create a new process, where the global variables will be separate between the parent and children. Most OS implementations will use copy-on-write semantics, meaning that both the parent and child process will use the same physical memory pages for all global variables until one of the processes attempts to edit the physical memory, at which point a copy of that page is made, so that now each process gets its own copy and does not see the other process's, so that the processes are isolated.

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

TL;DR version: with fork(), you don't see the other guy's changes; with pthread_create() you do.

like image 118
RarrRarrRarr Avatar answered Mar 07 '23 21:03

RarrRarrRarr