gpt4 book ai didi

c - 如何让线程正确执行

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:46 24 4
gpt4 key购买 nike

我正在 ubuntu linux 平台上使用 pthreads 编写一个 c 程序。我创建了一个子进程,我希望这个子进程创建多个线程来同时执行某些事情,为此我编写了下面给出的代码。

int main(){
initialize();
int pid;
pid=fork();
if(pid<0)
{
printf("\n Error ");
exit(1);
}
else if(pid==0)
{
printf("Hello I am child process\n");
pthread_t t1,t2;

pthread_create(&t1,NULL,say_hello,"hello from 1");
pthread_create(&t2,NULL,say_hi,"hi from 2");
//exit(0);
}
else
{
printf("\n Hello I am the parent process ");
printf("\n My actual pid is %d \n ",getpid());
//exit(1);
}
return c;
}`

void* say_hello(void* data){
char *str;
str = (char*)data;
while(1){
printf("%s\n",str);
sleep(1);
}
}

void* say_hi(void* data){
char *str;
str = (char*)data;
while(1){
printf("%s\n",str);
sleep(1);
}
}

我期待的输出首先是子进程的 printf 语句将执行,然后两个线程将继续并发执行,同时执行“hello from 1”和“hi from 2”,直到按下 ctrl+c。但是在执行 printf 语句后,它只执行线程一次或两次,然后程序终止。我如何获得该程序的正确行为?

最佳答案

在子进程中,主线程立即退出(通过从 main() 返回)。发生这种情况时,整个进程都会终止,包括其他线程。

有一个单独的pthread_exit() 函数,它只退出一个特定的线程。这可以在主线程上使用;使用此方法,其他线程可以继续运行。

关于c - 如何让线程正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48595106/

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