gpt4 book ai didi

C++ 线程错误 : pointer being freed was not allocated

转载 作者:行者123 更新时间:2023-11-28 05:59:44 27 4
gpt4 key购买 nike

我正在使用 C++ 进行线程处理并进行了一些测试并遇到了这个错误。

这是我的代码:

#include <iostream>
#include <thread>
#include <unordered_map>
#include <string>
#include <vector>

using namespace std;

static vector<string> thisVector;

void thread1() {
for (int i = 0; i < 400; i++){
thisVector.push_back(to_string(i));
}
cout << "Finished 1" << endl;
return;
}

void thread2() {
for (int i = 0; i < 400; i++){
thisVector.push_back(to_string(i));
}
cout << "Finished 2" << endl;
return;
}


int main(int argc, const char * argv[]) {
thread first(thread1);
thread second(thread2);
first.join();
second.join();
cout << "done threading" << endl;
cout << thisVector.size() << endl;
return 0;
}

奇怪的是,有时我得到正确的输出,所以 800。有时我得到的数字略低于那个数字,我不知道是什么原因???有时我会收到以下错误:

malloc: *** 对象 0x100400028 错误:未分配正在释放的指针

任何帮助将不胜感激!

谢谢

最佳答案

std::vector 不是线程安全的。您有两个执行线程同时修改相同的 std::vector。在这种情况下,对 std::vector 的操作应该由互斥体保护。

这样做的结果是未定义的行为。正如您所观察到的,有时它可能会工作,有时会产生错误的结果但程序成功完成,有时程序会崩溃。这就是“未定义行为”的意思。

关于C++ 线程错误 : pointer being freed was not allocated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512331/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com