代码如下:
#include <pthread.h>
#include <stdio.h>
void* fetch();
int main(int argc, char *argv[])
{
pthread_t tid;
pthread_create(&tid, NULL, &fetch, NULL);
}
void* fetch()
{
printf("start...\n");
int i;
for (i = 0; i < 100; i++)
{
printf("fetch...\n");
}
pthread_exit(0);
}
为什么这段代码在我运行多次后效果不佳。帮助!当我做 $gcc thread_test.c $./a.out 它什么也没打印出来! 当我运行更多时间时:
耶!打印出: 开始... 获取...
为什么?
最佳答案
当你的主线程退出时,你的程序也会退出。无法保证线程将如何调度; fetch
有时可能会在 main
退出之前运行,有时 main
将先退出。
如果你想等待子线程,你需要添加一个调用来加入它的线程。
int main(int argc, char *argv[])
{
pthread_t tid;
pthread_create(&tid, NULL, &fetch, NULL);
return pthread_join(tid, NULL);
}
调用pthread_join阻塞直到 ID 为 tid
的线程退出,这样可以保证所有 printf
调用都将被执行。
关于c - "printf"无法在线程上正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16893651/