我正在用 C 语言开发一个使用多线程的 Linux 应用程序。由主函数生成的线程完成大部分工作,因此通常最后完成。我看到一些奇怪的行为,我相信这是由于主线程在生成的线程有机会完成其工作之前终止。下面是一些示例代码来说明我正在讨论的内容:
#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;
}
当运行此代码时,来自清理函数的消息会打印两次,这是应该的,但其他时候,当它运行时,我有时会看到该消息仅打印一次,而其他时候我会看到它打印了三次或者根本没有。您可以在 main 函数中添加 sleep 函数来计算 main 函数终止需要多长时间。
我该怎么做才能让程序正常运行?我怀疑这与加入 child 有关,但我不完全理解加入的概念或如何将其应用于这种情况。
提前致谢!
最佳答案
是的,您应该“加入”线程。 “加入”线程只是意味着等待线程终止。换句话说,你会这样做
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
等待两个线程都终止。
编辑:如果您有一个子线程,而该子线程又创建了一个“孙子”线程,该怎么办?通常,无论是谁创建了线程,都应该等待它终止(“加入”它)。所以在这种情况下,子线程会在孙线程上调用phtread_join,而主线程会在子线程上调用join。
关于c - 线程终止问题(C 编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1725429/