在不同线程中运行的函数会产生奇怪的输出
Function running in a different thread produces weird outputs
你好,我是C++中多线程的新手。我正在使用C++11中可用的线程类,以便在不同的线程中运行函数,但不知何故,我从函数中得到的输出非常尴尬。这可能是因为不同的线程可能试图在同一时间执行相同的变量,从而导致冲突。请建议我应该如何修改代码,以便获得正确的输出。我发布了一个我正在尝试做的示例代码。这不是原始代码,但它只是显示了我原始代码的流程,因为我的原始代码太长了,无法发布。但这两种情况的问题仍然相同。
#include<iostream>
#include<thread>
using namespace std;
typedef struct {
int thread_id;
char *message;
}threadData;
int display(threadData *tData){
threadData *my_data;
my_data = (threadData *) tData;
cout << "Thread ID: " << my_data -> thread_id << endl;
cout << "Message: " << my_data -> message << endl;
return 0;
}
int main(){
threadData *data;
data = (threadData *)malloc(sizeof(threadData));
data->thread_id = 12;
data->message = "This is the message";
for (int i = 0; i<10; i++)
{
std::thread t1(display, data);
t1.detach();
}
return 0;
}
输出:
Thread ID: 12
Message: This is the messageThread ID:
12
Message: This is the message
Thread ID: 12
Message: This is the message
Thread ID: 12
Message: This is the message
Thread ID: 12
Message: This is the message
我读到的是for循环预计运行10次,但它只运行了4次,原因是在main函数中,你没有等待所有线程完成,所以主进程在其他线程有机会运行之前退出。'main需要睡眠一段时间,等待所有线程完成它们的工作。
我在这里没有看到竞争条件,因为所有线程都在读取,没有人向threadData写入。
由于线程不保证哪个先运行,您需要保护对共享资源的访问。最简单的方法是通过互斥。
std::mutex g_i_mutex; // protects g_i
typedef struct {
int thread_id;
string message;
}threadData;
int display(threadData *tData)
{
std::lock_guard<std::mutex> lock(g_i_mutex);
threadData *my_data;
my_data = (threadData *) tData;
cout << "Thread ID: " << my_data -> thread_id << endl;
cout << "Message: " << my_data -> message << endl;
return 0;
}
输出:
线程ID:12留言:这是留言线程ID:12留言:这是留言线程ID:12留言:这是留言线程ID:12消息:这是消息
我建议你多读一些关于线程概念的书。它背后的概念并不简单,从长远来看,仅仅准备一个现成的解决方案对你没有帮助。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 请解释"函数1(p1,p2,p3);"的输出
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 当使用通配符和null指针调用函数时,对输出的说明
- 为什么递归函数的最终输出是 5?
- C++ 构造函数未显示输出
- c++ 将成员函数的输出写入文本文件
- 简单函数并不总是返回预期的输出
- 当使用我在一个函数、另一个函数中修改的数组时,在我的输出中得到一个奇怪的负数
- GCC 仪器 - 是否可以自动输出函数的参数?
- 意外输出..函数绑定在虚拟表中的发生方式
- 输出函数调用日志文件
- C++:程序不输出函数返回值
- 通用化标准库容器的输出函数
- C++:int数组[a][b][C]={0};未将所有值设置为0.是那个指令错了,还是我的输出函数出了问题
- <</>>运算符重载和输入/输出函数之间的区别
- Ncurses 输出函数只接受常量数据