线程终止问题(C语言编程) [英] thread termination issue (c programming)

查看:646
本文介绍了线程终止问题(C语言编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Linux用C,它使用多线程的应用程序。这是由主要功能催生了线程做的大部分工作,因此通常最后完成。我看到一些奇怪的行为,我相信这是由于主线程终止前产生的线程有机会完成自己的工作。下面是一些示例code来说明我说的是:

I'm working on an application for Linux in C which uses multiple threads. The threads which are spawned by the main function do most of the work, and therefore usually finish last. I'm seeing some strange behavior, and I believe it's due to the main thread terminating before the spawned threads have a chance to finish their jobs. Here's some sample code to illustrate what I'm talking about:

#define _POSIX_C_SOURCE 200112L
#define _ISOC99_SOURCE
#define __EXTENSIONS__
#define _GNU_SOURCE

#include <pthread.h>
#include <stdio.h>

void
my_cleanup(void *arg)
{
     printf("cleanup: %s\n", (char *)arg);
}


void *
thread_stuff(void *arg)
{
     printf("thread started\n");
     pthread_cleanup_push(cleanup, "running");
     if (arg)
          pthread_exit((void *)2);
     pthread_cleanup_pop(0);
     pthread_exit((void *)2);
}


int
main()
{
     int err;
     pthread_t tid1, tid2;

     err = pthread_create(&tid1, NULL, thread_stuff, (void *)1);
     err = pthread_create(&tid2, NULL, thread_stuff, (void *)1);

     sleep(10);                 /* change the value here if you want */

     return SUCCESS;
}

在运行此code,印从清理功能的消息两次,因为它应该是,但有时在运行时,我看到消息只能打印一次,有时,其他时候我看到它印刷三次,或根本没有。您在主函数睡眠功能添加具有需要多长时间的主要功能终止播放。

When this code is run, the message from the cleanup function is printed twice, as it should be, but other times when it is run, I see the message printed only once sometimes, and other times I see it printed three times or not at all. You add in the sleep function in the main function to play with how long it takes the main function to terminate.

我能做些什么,使运行,因为它应该的计划?我怀疑它是与加入到孩子们,但我不明白全部的概念连接或如何将其应用到这种情况。

What can I do to make the program run as it should? I suspect it has something to do with joining to the children, but I don't entirely understand the concept of a join or how to apply it to this situation.

在此先感谢!

推荐答案

是的,你应该加入的线程。 加入一个线程仅仅意味着等待,直到线程终止。换句话说,你会怎么做。

Yes, you should "join" the threads. "Joining" a thread simply means waiting until the thread has terminated. In other words, you would do

pthread_join(tid1, NULL);
pthread_join(tid2, NULL);

要等到这两个线程都终止。

to wait until both threads have terminated.

编辑:如果你有一个子线程,这反过来,创建了一个孙子线程怎么办?作为一项规则,谁创建线程应该等待它终止(加入的话)。因此,在这种情况下,子线程会叫phtread_join孙子线程,而主线程会召唤加盟子线程上。

What to do if you have a child thread which, in turn, creates a "grandchild" thread? As a rule, whoever created the thread should wait for it to terminate ("join" it). So in this scenario, the child thread would call phtread_join on the grandchild thread, and the main thread would call join on the child thread.

这篇关于线程终止问题(C语言编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆