【发布时间】:2010-12-16 01:48:16
【问题描述】:
我正在开发一个使用多线程的 C 语言 Linux 应用程序。由 main 函数产生的线程完成了大部分工作,因此通常最后完成。我看到一些奇怪的行为,我相信这是由于主线程在生成的线程有机会完成它们的工作之前终止。下面是一些示例代码来说明我在说什么:
#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;
}
运行此代码时,清理功能的消息按应有的方式打印两次,但在其他时候运行时,我有时只看到消息打印一次,而其他时候我看到它打印了 3 次或者根本没有。在 main 函数中添加 sleep 函数来玩一下 main 函数终止需要多长时间。
我可以做些什么来让程序正常运行?我怀疑它与加入孩子有关,但我不完全理解加入的概念或如何将其应用于这种情况。
提前致谢!
【问题讨论】:
-
这是 stackoverflow.com/questions/1695106/… 和 stackoverflow.com/questions/1680224/posix-threads-problem 的副本 - 我愿意花很多钱这是最常见的 pthreads 问题(即使提问者有时不知道这是他们在问的问题!)
标签: c multithreading join posix pthreads