【发布时间】:2017-06-28 04:00:16
【问题描述】:
我有一个小问题,想知道是否有人可以提供帮助。我试图以最简单的方式证明我的问题。我试图通过引用多个线程来传递一个对象。每个线程都调用“doSomething”,它是属于对象“Example”的成员函数。 “doSomething”函数应该增加计数器。我的 gcc 版本是 4.4.7
问题:
为什么变量“counter”的值没有增加,尽管我通过引用线程函数传递了对象。
代码:
#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;
}
输出:
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
【问题讨论】:
-
你需要联锁增量
标签: c++ multithreading pass-by-reference