C 理解pthread_分离
下面的照片C 理解pthread_分离,c,pthreads,C,Pthreads,下面的照片 In Main() Hello World Hello World 为什么要把Hello World打印两次?如果使用pthread_join(),则会出现所需的输出(只有一个Hello World前面有一个In Main() #包括 void*thread_func(void*arg); int main(int argc,字符**argv) { int-s; 无效*res; pthread_t t1; s=pthread_create(&t1,NULL,thread_func,
In Main()
Hello World
Hello World
为什么要把Hello World打印两次?如果使用pthread_join(),则会出现所需的输出(只有一个Hello World前面有一个In Main()
#包括
void*thread_func(void*arg);
int main(int argc,字符**argv)
{
int-s;
无效*res;
pthread_t t1;
s=pthread_create(&t1,NULL,thread_func,“Hello World\n”);
如果(s!=0)
printf(“Err\n”);
printf(“在Main()\n中”);
s=pthread_detach(t1);
如果(s!=0)
printf(“Err\n”);
返回0;
}
void*thread_func(void*arg)
{
char*s=(char*)arg;
printf(“%s”,s);
pthread_退出(0);
}
我知道pthread_detach会告诉库在线程终止后释放pthread使用的所有资源……既然我在thread_func的末尾终止了它,一切都应该正常吧
我在这里遗漏了什么?在我看来,您使用的是标准库的非线程安全版本(打印、fflush…)。我已经看到过这种(显然)旧的类unix实时系统上的非逻辑行为。std库有两个不同版本,一个用于单线程模式,另一个用于多线程模式。当然,默认为单线程。。。
一般来说,对文件指针和类似内容的访问应该使用互斥体序列化。在您的程序中有两个线程终止,每个线程终止都可能希望隐式调用fflush,但由于底层缓冲区不打算同时访问,因此两个刷新都可能会将相同的数据写入输出文件描述符次要的一点:
char*s=(char*)arg;
应该是char*s=arg;
而且,这会为我打印“Hello World”0、1或2次。请记住,除非明确指定,否则线程不需要彼此等待,您在这里遇到的行为称为未指定行为(不是未定义的行为)这很好。我无法用您提供的代码重现问题。使用pthread\u detach
我只看到“Hello World”消息的一个副本。我尝试添加对sleep的调用(3)
在主线程中,确保线程有机会完成运行,但我仍然只看到一次消息。@H2CO3。我不确定如何执行此操作。与您一样,我也会收到0、1或2个Hello World。但是,对我来说,这在逻辑上没有意义(我是pthreads的新手)。您说该行为未指定,但如果您从逻辑上考虑,一旦线程\u func结束,线程就会终止执行。@JohnReddock:您没有包括printf
的头。哦,您是如何编译/链接的?
#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);
}