I have a small problem and wondering if someone can help. I tried to demonstrate my problem in the most simple way possible. I am trying to pass an object by reference to multiple threads. Every thread calls "doSomething" which is a member function that belongs to the object "Example". The "doSomething" function should increment the counter. My gcc version is 4.4.7
The questions:
why is the value of the variable "counter" is not incremented although I passed the object by reference to the thread function.
The code:
#include <iostream>
#include <thread>
class Exmaple {
private:
int counter;
public:
Exmaple() {
counter = 0;
}
void doSomthing(){
counter++;
}
void print() {
std::cout << "value from A: " << counter << std::endl;
}
};
// notice that the object is passed by reference
void thread_task(Exmaple& o) {
o.doSomthing();
o.print();
}
int main()
{
Exmaple b;
while (true) {
std::thread t1(thread_task, b);
t1.join();
}
return 0;
}
The output:
value from A: 1
value from A: 1
value from A: 1
value from A: 1
value from A: 1
value from A: 1
value from A: 1
value from A: 1
value from A: 1