gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:43:44 30 4
gpt4 key购买 nike

我有一个小问题,想知道是否有人可以提供帮助。我试图以最简单的方式展示我的问题。我试图通过引用多个线程来传递一个对象。每个线程调用“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

最佳答案

while (true) {
std::thread t1(thread_task, b);
t1.join();
}

这里你需要知道两件事:

  • 使用std::ref 传递引用。
  • 无限循环是C++中的未定义行为;

下面的工作示例:

#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;
for(int i =0; i < 10; i++) {
std::thread t1(thread_task, std::ref(b));
t1.join();
}
return 0;
}

输出:

value from A: 1
value from A: 2
value from A: 3
value from A: 4
value from A: 5
value from A: 6
value from A: 7
value from A: 8
value from A: 9
value from A: 10

查看Live .

尽管更进一步,您还应该考虑数据竞争

关于c++ - 通过引用传递对象和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42148629/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com