【问题标题】:How do I get threads to execute properly如何让线程正确执行
【发布时间】: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 相同,但代码不应依赖于该实现

标签: c pthreads


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这是因为创建线程的父线程终止,因为 main() 函数返回。当它退出时,线程也退出。 为了防止程序在线程完成其例程之前退出,您可以使用 pthread_join() 函数。

    例如,在您的情况下,在使用 pthread_create() 之后,在您创建的第一个线程上使用 pthread_join() 将阻塞父亲,直到您的第一个线程完成他的工作。 试试这个:

     pthread_create(&t1,NULL,say_hello,"hello from 1");
     //your second pthread_create
     pthread_join(th1, NULL);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 2019-09-17
      • 2016-07-09
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 2022-11-23
      相关资源
      最近更新 更多