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

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

有一个共享向量,其中包含可供两个线程访问的数据。但是当 运行 下面的代码。我收到一条错误消息,提到 分段错误(核心转储)。这里 std::vector<json> outputOfStealthAddresses 是共享向量。我在这里做的是每个线程都需要从向量中获取第一个值并将其存储在本地线程中,然后将其从向量中删除(避免从每个线程中重复使用)。这里我使用了一个 mutex 来锁定向量。然后将本地存储的数据传递给 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 插入? 如果是这样:这不会解决您的性能问题。你应该做的是: 将您的插入作为单个事务进行。