多线程程序中的核心转储:basic_string::_S_construct null无效
Core dump in multithreaded program: basic_string::_S_construct null not valid
我希望4个线程将进入名为read
的相同函数,并执行函数中的内容(读取,之后在监视器上打印,并显示所有内容…)。问题:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
trAborted (core dumped)
代码是:
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
struct v {
int id;
char* ad;
v(int a, char* t) {
id = a;
ad = t;
}
};
int bank = 1000;
pthread_mutex_t mutex;
void* read(void* argument)
{
cout << "tr";
v* d;
int num;
d = (v*) argument;
string l = d->ad;
int n = d->id;
string x = "";
ifstream textfile;
textfile.open(l.c_str());
while (!textfile.eof()) {
textfile >> x;
if (x == "SUB") {
pthread_mutex_lock(&mutex);
textfile >> num;
bank = bank - num;
cout << "person num " << n << " sub " << num << " dollars and know in the Bank: " << bank << endl;
pthread_mutex_unlock(&mutex);
}
if (x == "ADD") {
pthread_mutex_lock(&mutex);
textfile >> num;
bank = bank + num;
cout << "person num " << n << " add " << num << " dollars and know in the Bank: " << bank << endl;
pthread_mutex_unlock(&mutex);
}
if (x == "GET") {
pthread_mutex_lock(&mutex);
cout << "person num " << n << " look in the Bank: " << bank << endl;
pthread_mutex_unlock(&mutex);
}
}
textfile.close();
return 0;
}
int main(void)
{
pthread_mutex_init(&mutex, NULL);
int i = 0, j = 0;
v data1(1, "file1.dat"), data2(2, "file2.dat"), data3(3, "file3.dat"), data4(4, "file4.dat");
pthread_t t1, t2, t3, t4;
i = pthread_create(&t1, NULL, read, (void*)&data1);
if (i != 0) cout << "error" ;
j = pthread_create(&t2, NULL, read, (void*)&data2);
if (j != 0) cout << "error" ;
i = pthread_create(&t3, NULL, read, (void*)&data3);
if (i != 0) cout << "error" ;
j = pthread_create(&t4, NULL, read, (void*)&data4);
if (j != 0) cout << "error" ;
pthread_exit(NULL);
return 0;
}
在堆栈上传递线程数据,这几乎从来不是一个好主意。
当你调用pthread_exit
时,包含dataN
对象的主线程堆栈被释放。如果您的一个线程在pthread_exit
之后被调度,它将对已释放的对象进行操作。
最佳解决方案是通过new
在堆上分配data
对象。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- <string> 使用 for 循环写入向量
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串