【发布时间】:2019-05-15 21:35:00
【问题描述】:
也许我完全迷路了,但我正在尝试学习 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))...);
我想要的是能够在线程内运行时向对象写入和读取数据。这是要走的路吗?
【问题讨论】:
-
请提供仿真代码。作为旁注,“我想要的是能够在线程内运行时向对象写入和读取数据。这是要走的路吗?”取决于您未指定的工作量。您真正需要了解的是线程如何工作和性能权衡。这些是 IMO 在最低级别(组装)上最好的学习。
-
在编写线程代码时需要注意很多事情,尤其是线程之间的正确同步。我假设您的问题特别是您正在复制模拟,并且线程正在使用副本,但是还有其他同步问题可能导致使用
count的两个线程的未定义行为。跨度> -
已编辑!您可能知道,不写很多代码是一种简化。
-
@mukunda 我编辑了我的帖子。当我尝试作为参考传递时,我得到一个错误。我的解释是作为参考传递已被标记为已删除。
标签: c++ multithreading