为什么你认为你的所有线程都在休眠?读一些pthreads 教程 https://computing.llnl.gov/tutorials/pthreads/ & 并行线程(7) http://man7.org/linux/man-pages/man7/pthreads.7.html
看起来你的线程很快就终止了。你应该加入他们(例如在sleep
,或者里面的某个地方main
) using pthread_join(3) http://man7.org/linux/man-pages/man3/pthread_join.3.html
for (int i=0; i<2; i++) {
void* retval = NULL;
pthread_join(tid[i], &retval);
// in your case, since doSomething gives NULL :
assert (retval == NULL);
}
或者您应该创建独立的线程,请参阅pthread_创建(3) http://man7.org/linux/man-pages/man3/pthread_create.3.html&示例中pthread_attr_init(3) http://man7.org/linux/man-pages/man3/pthread_attr_init.3.html & pthread_attr_setdetachstate(3) http://man7.org/linux/man-pages/man3/pthread_attr_setdetachstate.3.html etc....
你应该已经编码了(因为你期望doSomeThing
得到一个NULL
争论):
void* doSomeThing(void* arg) {
assert (arg == NULL);
顺便说一句,请编译gcc -Wall -Wextra -g
并学习如何使用gdb
调试器。
你可能应该call 冲洗(3) http://man7.org/linux/man-pages/man3/fflush.3.html在适当的地方(因为stdio(3) http://man7.org/linux/man-pages/man3/stdio.3.html经常buffered http://en.wikipedia.org/wiki/Data_buffer),例如称呼fflush(NULL);
在......的最后doSomeThing
阅读未定义的行为 http://en.wikipedia.org/wiki/Undefined_behavior并努力避免它。
重要的是要做fflush(NULL);
在您期望输出的线程内部(至少在结束它们之前)。您的问题与以下内容无关sleep
但要缓冲。和printf
出于非常有效的性能原因,通常会被缓冲。你也应该戒掉这个习惯printf
格式化控制字符串\n
(因为这经常刷新缓冲区)。放一个\n
仅在一个开始时printf
格式化字符串是一个坏习惯(它应该在最后)。
顺便说一句,通过纠正void* doSomething(void*arg)
线(因为与void arg
正如问题的原始版本中给出的,代码甚至无法编译!)我在编译时观察到以下输出:
% gcc -Wall -g x.c -pthread -o xx
x.c: In function 'doSomeThing':
x.c:11:19: warning: unused variable 'i' [-Wunused-variable]
unsigned long i = 0;
^
然后执行:
% ./xx
Thread created successfully
First thread processing
Thread created successfully
Second thread processing
因此,问题中给出的代码在我的计算机上的行为并不如问题中所解释的那样。所以严酷的S·库尔什雷斯塔 https://stackoverflow.com/users/4207519/harsh-s-kulshrestha应该通过给出来编辑他的问题exact源代码,完整的编译命令,以及exact输出。 FWIW,我的系统是 x86-64 上的 Linux/Debian/Sid,gcc
是版本4.9.2,libc
是 Debian GLIBC 2.19-15