【发布时间】:2019-03-30 14:29:30
【问题描述】:
我正在学习 pthread。我发现如果我反复运行程序,下面代码的输出可能会很奇怪。 我以这样的方式编写线程1“等待”线程2,主线程“等待”线程1。这种方式是不正确的,因为当 thead1 开始运行时,线程 2 可能不可用,但我仍然想知道为什么线程 2 中的 printf 会被复制。谢谢!
#include <stdio.h>
#include <pthread.h>
#include <string.h>
pthread_t thread1;
pthread_t thread2;
void* thread1_entry(void* input)
{
int ret;
/* This may return error when thread2 has not been created yet*/
ret = pthread_join(thread2, NULL);
printf("hello from 1-%d-%s\n", ret, strerror(ret));
return 0;
}
void* thread2_entry(void* input)
{
printf("hello from 2\n");
printf("exit from 2.....\n");
return 0;
}
int main(void)
{
int ret1, ret2;
ret1 = pthread_create(&thread1, NULL, thread1_entry, NULL);
ret2 = pthread_create(&thread2, NULL, thread2_entry, NULL);
if (ret1 || ret2)
{
printf("error-%d-%d\n", ret1,ret2);
}
else
{
pthread_join(thread1, NULL);
}
return 0;
}
输出可能不一致(由于调度?),最奇怪的是线程 2 中的 printf 可能重复。
$ ./a.out
hello from 2
exit from 2.....
hello from 1-0-Success
$ ./a.out
hello from 1-0-Success
hello from 2
exit from 2.....
exit from 2.....
GCC 版本:
$ gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
【问题讨论】: