【问题标题】:Read/Write information to class in another thread读/写信息到另一个线程中的类
【发布时间】: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(&amp;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


【解决方案1】:

std::thread thread(&amp;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;
}

【讨论】:

    【解决方案2】:

    https://en.cppreference.com/w/cpp/thread/thread/thread 的示例部分演示了如何将类的成员函数和对该类实例的引用传递给std::thread。请参阅该示例编码中的std::thread t5(&amp;foo::bar, &amp;f);。

    这样,您应该能够在两个线程之间共享您的示例编码中的sim::Simulation 实例。 但是这将为共享对象/字段上的各种同步问题和竞争打开大门。因此,当您超出仅共享 count 时要小心,我认为它来自原子可写类型。

    【讨论】:

    • 感谢您的建议。现在线程正在工作,我可以开始了解多线程和资源访问的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 2012-09-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多