[英]Program calls printf() then loops forever. Why don't I see the printf output?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <math.h>
struct my_Struct{
int a;
int b;
};
void *myThreadFun(void *received_struct)
{
struct my_Struct *struct_ptr = (struct my_Struct*) received_struct;
printf("%.1lf",pow(struct_ptr->a,struct_ptr->b));
return NULL;
}
int main(int argc, char* argv[])
{
struct my_Struct s;
s.a = atoi(argv[1]);
s.b = atoi(argv[2]);
pthread_t thread_id;
pthread_create(&thread_id, NULL, myThreadFun, &s);
pthread_join(thread_id, NULL);
while(1);
exit(0);
}
为什么这段代码什么都不做? 它应该在生成的线程中打印语句,然后进入无限循环。
使用gdb我们可以看到线程分叉成功
[New Thread 0x7ffff7a2d640 (LWP 8261)]
[Switching to Thread 0x7ffff7a2d640 (LWP 8261)]
Thread 2 "a.out" hit Breakpoint 1, myThreadFun (received_struct=0x7fffffffd960) at tmp.cpp:15
如果删除while(1)
,则可以找到输出。 输出延迟可能与 stdio 的缓冲区有关, while(1)
阻止了缓冲区刷新。
您可以尝试另一种方法:添加fflush(stdout);
在printf
之后,它的工作原理相同。
这是因为stdout
缓冲整行,所以这意味着它不会打印您的值,直到您执行以下三件事之一:
\\n
结束你的字符串: printf("%.1lf\\n", ...)
fflush(stdio)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.