线程同步未获得预期的输出
Thread Synchronization not getting expected output
我没有得到任何输出,但我希望输出,因为THREAD1 THREAD2下面是代码。。
#include<iostream>
#include<pthread.h>
using namespace std;
void* fun(void *arg)
{
char *msg;
msg = (char*)arg;
cout<<msg<<endl;
}
int main()
{
pthread_t t1,t2;
t1 = pthread_create(&t1,NULL,fun,(void*)"THREAD1");
t2 = pthread_create(&t2,NULL,fun,(void*)"THREAD2");
pthread_join(t1,NULL);
pthread_join(t2,NULL);
// sleep (2);
return 0;
}
我把上面的代码改成了
pthread_create(&t1,NULL,fun,(void*)"THREAD1");
pthread_create(&t2,NULL,fun,(void*)"THREAD2");
现在我得到了THREAD2 THREAD1,但我需要THREAD1 THREAD2
现在我把代码改为>
pthread_create(&t1,NULL,fun,(void*)"THREAD1");
pthread_join(t1,NULL);
pthread_create(&t2,NULL,fun,(void*)"THREAD2");
pthread_join(t2,NULL);
现在我的结果是正确的THREAD1 THREAD2
t1 = pthread_create(&t1,NULL,fun,(void*)"THREAD1");
这不好。pthread_create
返回一个整数返回码,而不是pthread_t
。您正在用不应该存在的东西覆盖t1
和t2
,随后的pthread_join
调用可能会崩溃或产生不可预测的结果。
int rc1 = pthread_create(...);
if (rc1 != 0) {
// handle error
}
此外,fun
需要按照您定义的方式返回something。或者将其返回类型更改为void。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 来自不同线程的同步输出流
- 正在将输出同步到std::cout
- 同步主程序和 QProcess 之间的输出
- 同步STD cout输出多线程
- 关闭同步时的输出速度
- 线程同步未获得预期的输出