小编Saa*_*out的帖子

通过引用传递对象和多线程

我有一个小问题,想知道是否有人可以提供帮助.我试图以最简单的方式证明我的问题.我试图通过引用传递一个对象多个线程.每个线程调用"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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

value from A: 1
value from A: …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading pass-by-reference

2
推荐指数
1
解决办法
3939
查看次数

标签 统计

c++ ×1

multithreading ×1

pass-by-reference ×1