为同一向量C++运行多个线程时出现分段错误

Segmentation fault when running multiple threads for same vector C++

本文关键字:线程 错误 分段 向量 C++ 运行      更新时间:2023-10-16

有一个共享向量,其中包含两个线程访问的数据。但是当在代码下面运行时。我收到一个错误,提到分段错误(核心转储(。这里std::vector<json> outputOfStealthAddresses是共享向量。在这里,我所做的是每个线程都需要从向量中获取第一个值并将其本地存储在线程中,然后将其从向量中删除(避免每个线程的双重使用(。在这里,我使用互斥锁来锁定向量。然后本地存储的数据传递到 SQLite 连接以将数据插入到数据库中。

注意 -在这里,我为每个线程使用两个SQLite连接。

下面是两个线程函数。

线程 1 函数

void runSaDataStoreThread1(){
//creating sqlite connection
indexMapper::indexes dbConnectionSA ("file", "sub-file","data" ,true );    //init database instance globally
//create data table for tx details
dbConnectionSA.createTable(saDetailTable);
while (true){
if(!outputOfStealthAddresses.empty()){
std::vector<json> temp;
mtx.lock();
if(!outputOfStealthAddresses.empty()){
temp.push_back(outputOfStealthAddresses[0]);
outputOfStealthAddresses.erase(outputOfStealthAddresses.begin());
}
mtx.unlock();
if(!temp.empty()){
dbConnectionSA.insertSAData(temp[0]);
}
temp.erase(temp.begin());
}else if(outputOfStealthAddresses.empty() && isAllBlockDone){
break;
}
}
dbConnectionSA.close();
}

线程 2 函数

void runSaDataStoreThread2(){
//creating sqlite connection
indexMapper::indexes dbConnectionSA1 ("file", "sub-file","data-2" ,true );    //init database instance globally
//create data table for tx details
dbConnectionSA1.createTable(saDetailTable);
while (true){
if(!outputOfStealthAddresses.empty()){
std::vector<json> temp2;
mtx.lock();
if(!outputOfStealthAddresses.empty()){
temp2.push_back(outputOfStealthAddresses[0]);
outputOfStealthAddresses.erase(outputOfStealthAddresses.begin());
}
mtx.unlock();
if(!temp2.empty()){
dbConnectionSA1.insertSAData(temp2[0]);
}
temp2.erase(temp2.begin());
}else if(outputOfStealthAddresses.empty() && isAllBlockDone){
break;
}
}
dbConnectionSA1.close();
}

主要功能

int main(){
auto thread11 = std::thread(parse::runSaDataStoreThread1);
auto thread16 = std::thread(parse::runSaDataStoreThread2);
thread11.join();
thread16.join();
}

您需要使用互斥锁保护对向量方法的所有调用。具体来说,empty()调用。

至于你的具体问题:

您需要使用互斥锁来锁定向量上的所有操作。

至于你实际上似乎试图解决的问题: 我假设您想通过并行化来加快 SQLite 插入的速度? 如果是这样:这不会解决您的性能问题。你应该做的是: 将插入作为单个事务进行。