0

Async and mutex

Hi All I have a vector<string>. This vector is nothing but path of text files which i need to read. In for loop of the vector, I am creating a async with launch::async for each individual file. This function which is responsible to read individual file is reading text file line by line and adding all data into common queue. Here. in function while adding data in queue, mutex is required or not? I could observe that with and without mutex, output is not different. Also reading sequence is also not sample. Code is not working on SL platform due to input files, but sample code is at below: inside main function: { ThreadPool obj_Pool; //vector<future<bool>> result = obj_Pool.ReadAllInputFiles(strBasePath, vecAllInputFiles); cout << "Hi Reading is done" << endl; cout << obj_Pool.cnt << endl; } inside all read file function for (int i = 0; i < (int)vecAllInputFiles.size(); ++i) { string strFilePathWidNameExtension = strBasePath + "\\" + vecAllInputFiles[i]; std::async(launch::async,&ThreadPool::ReadOneFile,this,strFilePathWidNameExtension); } inside readonefile function: //open file fstream objInputFile; objInputFile.open(strFilePathWidNameExtension, ios::in); //check if file is open or not if (objInputFile.is_open()) { string strLine; while (getline(objInputFile, strLine)) { { cout << strFilePathWidNameExtension << endl; unique_lock<mutex> locker(m_mutexQueue_Lines); m_queueTasks_Lines.push(strLine); cnt++; } } //close the file objInputFile.close(); }

10th Mar 2021, 6:29 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
1 Answer
+ 1
I suppose this reply is a little late. If you are updating a shared resource (the queue) with multiple asynchronous threads (readonefile), then the answer is yes, you must use a mutex in order to guard against race conditions where threads might overwrite each other's queue entries. The likelihood of this happening increases with multiple core processors where threads can actually run in parallel.
23rd Mar 2021, 8:29 PM
Brian
Brian - avatar