这是我的第一个pthread程序,我不知道为什么在子线程中将printf语句打印两次:
int x = 1;
void *func(void *p)
{
x = x + 1;
printf("tid %ld: x is %d\n", pthread_self(), x);
return NULL;
}
int main(void)
{
pthread_t tid;
pthread_create(&tid, NULL, func, NULL);
printf("main thread: %ld\n", pthread_self());
func(NULL);
}
在我的平台(Linux 3.2.0-32-通用#51-Ubuntu SMP x86_64 GNU/Linux)上观察到的输出:
1.
main thread: 140144423188224
tid 140144423188224: x is 2
2.
main thread: 140144423188224
tid 140144423188224: x is 3
3.
main thread: 139716926285568
tid 139716926285568: x is 2
tid 139716918028032: x is 3
tid 139716918028032: x is 3
4.
main thread: 139923881056000
tid 139923881056000: x is 3
tid 139923872798464tid 139923872798464: x is 2
对于3,子线程有两条输出线
4,与3相同,甚至输出是交错的。
最佳答案
似乎真正的答案是Michael Burr的评论,其中引用了此glibc错误:https://sourceware.org/bugzilla/show_bug.cgi?id=14697
总而言之,glibc在程序退出期间无法正确处理stdio缓冲区。
关于pthreads - pthread : one printf statement get printed twice in child thread,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13550662/