gpt4 book ai didi

c++ - fork 命令是否适用于多线程应用程序?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:24:12 25 4
gpt4 key购买 nike

我试图创建一个多线程应用程序。似乎 fork 还没有复制我的第二个线程。

这是我的代码:

#include <stdlib.h>
#include <pthread.h>
#include <iostream>
#include <linux/unistd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ioctl.h>

using namespace std;

void Loop(const char* zThread)
{
while (true)
{
sleep(2);
cout << "LOOP : " << zThread << " : " << getpid() << endl;
}
}

void *MyFunction(void *pData)
{
Loop("Second");
};

int main()
{
pthread_t thread1;

pthread_create(&thread1, NULL, MyFunction, NULL);

int iPID = fork();

if (iPID == 0)
cout << "Child : " << getpid() << endl;
else
cout << "Parent : " << getpid() << endl;

Loop("First");

return EXIT_SUCCESS;
};

它给出以下输出,其中不包含子进程的第二个线程写入的任何信息。

test_1/ss> ./a.out
Parent : 11877
Child : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879

第二个线程怎么了?

最佳答案

只有调用线程被 fork 。

来自docs :

A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources. Consequently, to avoid errors, the child process may only execute async-signal-safe operations until such time as one of the exec functions is called.

关于c++ - fork 命令是否适用于多线程应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24806224/

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