为什么' pthread '没有输出?
why there is no output for `pthread`?
#include <pthread.h>
#include <stdio.h>
typedef struct thread_char_para {
char character;
int count;
} thread_char_para;
void* char_print (void* parameter)
{
thread_char_para* p = (thread_char_para*)parameter;
int i;
for (i = 0; i < p->count; ++i)
fputc(p->character, stderr);
return NULL;
}
int main()
{
pthread_t thread1;
pthread_t thread2;
thread_char_para para1 = {'x', 30000};
thread_char_para para2 = {'o', 30000};
pthread_create(&thread1, NULL, char_print, ¶1);
pthread_create(&thread2, NULL, char_print, ¶2);
return 0;
}
为什么没有任何输出?
我也找到了一些链接来阅读:分离与可接合的POSIX线程
在这个链接中,它说pthread_join
是不必要的。所以,我想知道。
您需要在pthread_create()
之后调用pthread_join()
或pthread_exit()
,否则main()
也将返回杀死派生线程。
作为连接两个线程的另一种选择,可以像对待任何其他线程一样对待main()
-线程,并使用pthread_exit()
退出。
这样做会防止进程和所有的线程在main()
返回的那一刻结束。
您应该添加pthread_join
调用,以确保您的main
函数等待其他线程完成:
int main()
{
pthread_t thread1;
pthread_t thread2;
thread_char_para para1 = {'x', 30000};
thread_char_para para2 = {'o', 30000};
pthread_create(&thread1, NULL, char_print, ¶1);
pthread_create(&thread2, NULL, char_print, ¶2);
pthread_join(thread1, NULL); // <-- add these
pthread_join(thread2, NULL); // <--/ two lines.
return 0;
}
要给您一个关于何时可以避免pthread_join的示例,请查看下面的代码
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
typedef struct thread_char_para {
char character;
int count;
} thread_char_para;
void* char_print (void* parameter)
{
thread_char_para* p = (thread_char_para*)parameter;
int i;
if (p->character == 'x')
{
pthread_t thread2;
thread_char_para para2 = {'o', 30000};
pthread_create(&thread2, NULL, char_print, ¶2);
for (i = 0; i < 5; ++i)
{
sleep(1);
}
}
else
{
for (i = 0; i < p->count; ++i)
fputc(p->character, stderr);
}
return NULL;
}
int main()
{
pthread_t thread1;
thread_char_para para1 = {'x', 30000};
pthread_create(&thread1, NULL, char_print, ¶1);
pthread_join(thread1, NULL);
return 0;
}
可以看到,main
启动pthread1
,等待pthread1
完成。pthread1
启动另一个thread2
并循环5秒,而pthread2
正在做它的工作。在这种情况下,不使用pthread_join
。
从main
函数返回相当于调用exit
。它杀死进程及其所有线程。因此,您的程序在线程有机会运行之前杀死它们。pthread_create
并不意味着线程在pthread_create
内执行,它意味着线程将在未来的某个时刻执行,创建线程后做的第一件事就是杀死它们,这使得它们很可能还没有机会开始运行。
你可以用不同的方法来解决这个问题。正如其他人提到的那样,您可以等到线程使用pthread_join
完成运行,您可以让线程通过管道、信号量、屏障、条件变量和许多其他方式向main指示它们已经完成。你只需要确保main
在线程完成之前不能返回,否则你很可能会在它们有机会运行之前杀死它们。
pthread_join
是不必要的,因为你提到的答案说。在您的情况下,等待线程完成运行是最简单的方法。严格地说,你甚至不需要等待线程结束运行,你只需要它们向主线程表明它们已经完成了你想让它们做的事情,线程完成是知道它们已经开始运行的最简单的方法。
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- pthread没有给出预期的输出
- pthread分配输出错误
- Pthread冻结标准输出
- 使用pthread的简单程序的输出
- 为什么' pthread '没有输出?
- 如何在c++中使用pthread或诅咒同时向屏幕输出多个字符串