user3264565
user3264565

Reputation: 61

Error while coding a multi threaded program with boost library

I have created two threads which would execute a single piece of code parallely.I want to run another method when the two threads have finished execution.I have tried join() and timed_join(),but it is not working.I am using boost thread class.Please find below my code:

Code:

A class:
A a;
boost::thread t(boost::bind(&A::method1,&a,s1,e1));//Call method1 using two parameters     s1 and e1.boost bind is used to call class methods
boost::thread t1(boost::bind(&A::method1,&a,s2,e2));//Call method1 using two parameters   s2 and e2.boost bind is used to call class methods.
t.join();
t1.join();
methodToBeExecutedAfterThreadExec();

Let me know how to execute a method1 parallely using threads and then i have to call methodToBeExecutedAfterThreadExec() method.

Thanks in advance.

Edit 1:

void method1(int start,int end)
{
    vector< vector<string> >::iterator row;
vector<string>::iterator col;
db.onAutoVacuumMode();//Vacuum mode is set to true which eliminates fragmentation
db.startTransaction();//Starts the transaction which does the stuff in a batch wise
for (row = dupViewResults.begin()+start; row != dupViewResults.begin()+end; ++row) {

    std::string filedata=readFileDataInStr(row->at(0));
    int x = boost::lexical_cast<int>( row->at(1) );
    long long int fileCRC32=MurmurHash(filedata.c_str(),x,0);
    std::string strCRC32=std::to_string(fileCRC32);
    std::string query="update duplicatesview set CRC32='"+strCRC32+"' where Filepath='"+row->at(0)+"'";
    char* charQuery = &query[0];
    db.fireSQLQuery(charQuery,results); 
 }
 db.endTransaction();
}

The above code would read the vector dupViewResults(which is already populated by my code)and then update the view and then fire sql query in a transaction.Thanks

Upvotes: 0

Views: 99

Answers (1)

David Schwartz
David Schwartz

Reputation: 182743

Based on your comments, it sounds like your db member is not thread safe. For example, when you call endTransaction on it, it has no way to know which transaction to end.

You have three choices, some of which may not work depending on details you haven't provided:

  1. Each thread could have its own database object.

  2. The database object could return a "transaction" object that subsequent functions take. Each thread could allocate its own transaction object.

  3. The database object could associate operations with the thread that calls it, knowing that endTransaction ends the transaction started by that same thread.

If you're going to call into a database from multiple threads at the same time, the database must be thread safe.

Upvotes: 2

Related Questions