下面是打印结果
In Main()
Hello World
Hello World为什么这个打印Hello World两次?如果我使用pthread_join(),就会出现所需的输出(只有一个Hello World前面有Main()。
#include <pthread.h>
void *thread_func(void *arg);
int main(int argc, char **argv)
{
int s;
void *res;
pthread_t t1;
s = pthread_create(&t1, NULL, thread_func, "Hello World\n");
if (s != 0)
printf("Err\n");
printf("In Main()\n");
s = pthread_detach(t1);
if (s != 0)
printf("Err\n");
return 0;
}
void *thread_func(void *arg)
{
char *s = (char *)arg;
printf("%s", s);
pthread_exit(0);
}我知道pthread_detach告诉库在线程终止后释放pthread使用的所有资源……既然我在thread_func的末尾终止了它,那么一切都应该没问题了,对吧?
这里我漏掉了什么?
发布于 2012-11-10 16:34:53
在我看来,您使用的是标准库的非线程安全版本(print、fflush...)。我已经在一个旧的类unix实时系统上看到过这种(显然)非逻辑的行为。std库有两个不同的版本,一个用于单线程模式,一个用于多线程模式。当然,默认的是单线程...一般来说,对文件指针和类似东西的访问应该用互斥锁来序列化。
https://stackoverflow.com/questions/13319793
复制相似问题