有关Linux进程与线程数目计算的问题

问题的提出:

       Linux,一个进程有n个线程,每个线程又使用fork()创建了一个进程?

      请问:总共有多少线程和进程?

 

问题的解答:

    

    Alexander AmelkinAccording to POSIX, after a fork() only the calling thread is to be cloned and all thread-related entities are not guaranteed to work (and in fact will NOT work). POSIX has a list of functions that are safe to use after fork() and most of the thread-related functions aren't on that list. Actually, there is a good explanation given in the Rationale section of the fork() description in POSIX1. In a few words, it says that fork() in a threaded application is only truly safe to use when it is almost immediately followed by exec().

Now, to answer your question. There will be your process with n threads plus n processes with 1 thread each. That totals n+1 processes and 2*n threads.

 

Yuri Perepechkinhttp://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html
fork - create a new process
A process shall be created with a single thread.
the new process shall contain a replica of the calling thread

Process/Threads:
* --fork-> 1/1

...
* --fork-> n-1/1

* --fork-> n/1


Total
processes: 1+n
threads: n+(n*1)=2n
Assumed each process must have one thread at least (main thread)
Start thread and process numeration from 1.


Daya Shanker PrasadThank you all, for your answer. For a long time I used to think about it but couldn't pay time on this. Finally I experimented this and got:
Thread: 2n + 1
Process: n + 1
main() was running as separate thread which was forking n threads.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值