How many processes and threads will be created? How many processes and threads will be created? multithreading multithreading

How many processes and threads will be created?


Actually, there should be 8 threads and 6 processes.

Here's the diagrams to make it clear:

1) after first fork():   |-------------------  child of p0 [p1]---|-------------------  parent      [p0]2) after second fork():       |---------------  child of p1 [p2]   |---|---------------              [p1]---|-------------------              [p0]3) after pthread_create():            -----------  thread 1 of p2 [p2t1]        |---/-----------  thread 0 of p2 [p2t0]       |    -----------  thread 1 of p1 [p1t1]   |---|---/-----------  thread 0 of p1 [p1t0]---|-------------------                 [p0]4) after third fork():         |------------ child of p2 [p5]         |      ------             [p2t1]       |-|-----/------             [p2t0]       |   |---------- child of p1 [p4]       |   |    ------             [p1t1]   |---|---|---/------             [p1t0]   |     |------------ child of p0 [p3]---|-----|------------             [p0]

important: Remember that the fork(2) call clones just the thread which executed it, thus process 4 [p4] has only one thread (same apply to process 5[p5]).


One extra process will get created each time fork is called.

On first call to fork, parent process P creates sub-process SP1.After fork, parent process calls fork again (skipping the if), creating sub-process SP2.

SP1 after fork calls fork inside if, creates sub-sub-process SSP1.SP1 then spawns a thread.SP1 leaves the if. and calls fork again, creating sub-sub-process SSP2.

SSP1 spawns a thread.SSP1 leaves the if, and calls fork, creating sub-sub-sub-process SSSP.

So, processes created: SP1, SP2, SSP1, SSP2, SSSP = 5 processes.If you count the original process P, there are 6 processes.

Only SP1 and SSP1 spawn threads, so there are 2 threads created. If you count all the main threads of all the processes, there are 7 or 8 threads, depending on whether or not you count the original process P.

An illustration of the processes and threads being created correlated to the code.

                         Ppid t pid;               |pid = fork();            +------SP1if (pid == 0) {          |      | fork();                 |      +---------------SSP1 thread create(...);     |      |-SP1's thread  |-SSP1's thread}                        |      |               |fork();                  +-SP2  +-SSP2          +-SSSP                         | |    | |             | |


shouldn't it be 2 threads and 6 processes?

M|  ↘M     A|     |↘M     A*   B*|     |    || ↘   | ↘  |↘M   C A  D B  E

as I use * to represent thread.