【发布时间】:2011-09-05 07:00:06
【问题描述】:
我想从主线程开始一个新线程。我不能使用 join,因为我不想等待线程退出然后继续执行。
基本上我需要的是 pthread_start(...) 之类的东西,但是找不到。
编辑:
由于所有答案都建议 create_thread 应该启动线程,问题是在下面的简单代码中它不起作用。下面程序的输出是“主线程”。似乎子线程从未执行过。知道我哪里错了吗?
在 Fedora 14 GCC 版本 4.5.1 上编译和运行
void *thread_proc(void* x)
{
printf ("sub thread.\n");
pthread_exit(NULL);
}
int main()
{
pthread_t t1;
int res = pthread_create(&t1, NULL, thread_proc, NULL);
if (res)
{
printf ("error %d\n", res);
}
printf("main thread\n");
return 0;
}
【问题讨论】:
-
程序的输出是什么?可能的原因见user396672的回答(主线程结束,os在子线程完成之前杀死所有线程)。
-
如果您从
main发送return,您的程序将终止。改为在主线程中调用pthread_exit。 -
或者只是添加 pthread_join(t1, NULL);返回 0 之前;
标签: c++ c linux multithreading pthreads