【发布时间】:2018-02-03 07:39:10
【问题描述】:
我正在 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 语句之后,它只在程序终止时只执行一个或两次线程。如何获得该程序的正确行为?
【问题讨论】:
-
贴出的代码无法编译!您是否希望我们猜测您省略了哪些部分?请发帖minimal reproducible example
-
线程应该以
return NULL;或(更好)pthread_exit( NULL );结尾 -
主进程需要等待子进程完成。最简单的方法是调用
wait()孩子需要等待线程完成。最简单的方法是::pthread_join( t1. NULL );后跟pthread_join( t2, NULL ); -
注意:调用
fork()返回的类型是pid_t。目前,与int相同,但代码不应依赖于该实现