S
Saeed Amrollahi
Hi
I have the following very simple multi-thread program:
#include <thread>
#include <mutex>
int var = 0;
void incr()
{
std::mutex m;
m.lock();
var++;
m.unlock();
}
int main()
{
std::thread t{incr};
std::mutex m;
m.lock();
++var;
m.unlock();
t.join();
return 0;
}
This is really simple program, and I think,
I made a mutual exclusion, when two threads
are writing shared variable (var).
But, when I run valgrind cmd , it turns out there is
data race. I used the following commands under Linux (GCC 4.7.0):
$ g++ -std=c++11 -pthread -pedantic -Wall simple_data_race.c++
$ valgrind -q --tool=helgrind ./a.out
Here it is the <abbreviated> valgrind messages:
<Message>
....
Possible data race during write of size 8 at <address> by thread #1
....
This conflicts with a previous write of size 8 by thread #2
....
</Message>
I struggled a few hours with such a simple code.
Please shed some light.
TIA,
-- Saeed Amrollahi Boyouki
I have the following very simple multi-thread program:
#include <thread>
#include <mutex>
int var = 0;
void incr()
{
std::mutex m;
m.lock();
var++;
m.unlock();
}
int main()
{
std::thread t{incr};
std::mutex m;
m.lock();
++var;
m.unlock();
t.join();
return 0;
}
This is really simple program, and I think,
I made a mutual exclusion, when two threads
are writing shared variable (var).
But, when I run valgrind cmd , it turns out there is
data race. I used the following commands under Linux (GCC 4.7.0):
$ g++ -std=c++11 -pthread -pedantic -Wall simple_data_race.c++
$ valgrind -q --tool=helgrind ./a.out
Here it is the <abbreviated> valgrind messages:
<Message>
....
Possible data race during write of size 8 at <address> by thread #1
....
This conflicts with a previous write of size 8 by thread #2
....
</Message>
I struggled a few hours with such a simple code.
Please shed some light.
TIA,
-- Saeed Amrollahi Boyouki