dimanche 10 juin 2018

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

There is a shared vector with data to access by two threads. But when running below code. I got an error mentioning that Segmentation Fault (core dump). Here std::vector<json> outputOfStealthAddresses is the shared vector. Here I'm doing is each thread need to get the first value from the vector and store it locally in the thread, then remove it from the vector (avoid double use from each thread). Here I used a mutex to lock the vector. Then locally stored data passed to the SQLite connection to insert the data in to the database.

Note - Here I'm using two SQLite connections for each thread.

Here are the two thread functions.

Thread 1 function

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();
}

Thread 2 function

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();
}

main function

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

  thread11.join();
  thread16.join();
}

Aucun commentaire:

Enregistrer un commentaire