Search code examples
multithreadingforkpid

How many processes and threads will be created?


I have this code and trying to understand how many process and threads will be created from this:

pid t pid; 
pid = fork(); 
if (pid == 0) { /* child process */ 
 fork(); 
 thread create( . . .); 
} 
fork(); 

I think it creates 2 threads, from the fork inside the if loop. and 8 processes? But Im not sure if thats right


Solution

  • 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]).