将创建多少个进程和线程? [英] How many processes and threads will be created?

查看:131
本文介绍了将创建多少个进程和线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,并试图了解由此将创建多少个进程和线程:

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(); 

我认为它从if循环内的fork创建了2个线程.和8个过程?但是我不确定那是否正确

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

推荐答案

实际上,应该有8个线程和6个进程.

Actually, there should be 8 threads and 6 processes.

以下是清楚说明图表:

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]

重要:请记住 fork(2) call仅克隆执行该线程的线程,因此进程4 [p4]只有一个线程(与进程5 [p5]相同).

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

这篇关于将创建多少个进程和线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆