gpt4 book ai didi

c++ - 读/写信息到另一个线程中的类

转载 作者:行者123 更新时间:2023-11-28 01:21:17 25 4
gpt4 key购买 nike

也许我完全迷路了,但我正在尝试学习 C++ 中的线程,但这段代码运行得不是很好:

相关代码为

TEST_F(TestSimulation, run_could_be_closed) {
sim::Simulation simulation;
std::thread thread(simulation);
while (simulation.getCount() < 15000) {
// wait
}
simulation.dispose();
}
void sim::Simulation::run() {  
while (isRunning) {
std::cout << "Processing information" << std::endl;
count++;
}
}

void sim::Simulation::dispose() {
isRunning = false;
}

int sim::Simulation::getCount() {
return count;
}
void sim::Simulation::operator()() {
init();
run();
}

似乎 Thread 类创建了作为参数发送的对象的拷贝,所以当我在主线程中调用 simulation.getCount() 时,它总是返回 0。

当我尝试将 std::thread thread(&simulation); 作为引用传递时,我得到一个错误

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:336:5: error: attempt to use a deleted function
__invoke(_VSTD::move(_VSTD::get<1>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);

我想要的是能够在线程内运行时向对象写入和读取数据。这是要走的路吗?

最佳答案

std::thread thread(&simulation);线程初始化错误

这是一个类似的例子

class Simulation {
public:
Simulation() : count(0), isRunning(true) {}

void Simulation::run() {
while (isRunning) {
std::cout << "Processing information" << std::endl;
count++;
}
}

void Simulation::dispose() { isRunning = false; }

int Simulation::getCount() { return count; }

private:
int count;
bool isRunning;
}

int mian() {

Simulation simulation;
std::thread thread(&Simulation::run, &simulation);
while (simulation.getCount() < 15) {
// wait
}
simulation.dispose();
simulation.join();
cout << simulation.getCount() << endl;

return 0;
}

关于c++ - 读/写信息到另一个线程中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56157938/

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