gpt4 book ai didi

c - 多线程程序创建新进程时会发生什么?

转载 作者:行者123 更新时间:2023-12-03 12:52:02 25 4
gpt4 key购买 nike

我想详细了解一下,如果一个带有多个线程的C程序创建新进程会发生什么,我有点困惑。行为是否取决于正在创建新进程的线程或多少线程创建了新进程?

最佳答案

使用pthreads时,在调用fork时,仅在新进程中派生了调用线程。

Linux man page:

The child process is created with a single thread--the one that called fork(). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of
pthread_atfork(3) may be helpful for dealing with problems that this can cause.



但是,Solaris上的某些 fork版本重复了所有线程。

Solaris man page:

A call to forkall() or forkallx() replicates in the child process all of the threads (see thr_create(3C) and pthread_create(3C)) in the parent process. A call to fork1() or forkx() replicates only the calling thread in the child process.

A call to fork() is identical to a call to fork1(); only the calling thread is replicated in the child process. This is the POSIX-specified behavior for fork().

In releases of Solaris prior to Solaris 10, the behavior of fork() depended on whether or not the application was linked with the POSIX threads library. When linked with -lthread (Solaris Threads) but not linked with -lpthread (POSIX Threads), fork() was the same as forkall(). When linked with -lpthread, whether or not also linked with -lthread, fork() was the same as fork1().

关于c - 多线程程序创建新进程时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35304570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com