问题的提出:
Linux,一个进程有n个线程,每个线程又使用fork()创建了一个进程?
请问:总共有多少线程和进程?
问题的解答:
Alexander Amelkin • According 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 Perepechkin •http://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 Prasad •Thank 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.