In my main function, I am trying to implement multithreading similar to below,
#include <thread>
#include <mutex>
....
int main(int argc, char *argv[])
{
std::mutex myMutex;
while(...) {
//some code
std::thread t1([=,&myArr](){
std::lock_guard<std::mutex> lockGuard(myMutex);
for(int i=0; i<1000; i++) {
myArr[i] = alpha*(myArr[i] - t*myArr[i-1]) ;
}
});
std::thread t2([=,&myArr](){
std::lock_guard<std::mutex> lockGuard(myMutex);
for(int i=1000; i<2000; i++) {
myArr[i] = alpha*(myArr[i] - t*myArr[i-1]) ;
}
});
t1.join();
t2.join();
}
return 0;
}
When I run the code like this myArr array is not updated as I wanted. Because of race condition. And ´´´lock_guard´´´ should help to solve this issue from my web search. But I am a bit confused about how to add that to this piece of code. I tried directly adding like below:
{
t1.join();
std::lock_guard<std::mutex> lockGuard(myMutex);
}
{
t2.join();
std::lock_guard<std::mutex> lockGuard(myMutex);
}
But it gives error : mycode.cpp:2127: error: binding reference of type ‘std::lock_guard::mutex_type& {aka std::mutex&}’ to ‘const std::mutex’ discards qualifiers std::lock_guard lockGuard(myMutex);
Is there any intelligent way to solve this issue?