在另一个线程中读取/写入信息

Read/Write information to class in another thread

本文关键字:信息 读取 另一个 线程      更新时间:2023-10-16

也许我已经完全迷失了,但是我正在尝试学习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();
}

似乎线程类创建了作为参数发送的对象的副本,因此当我在主线程中调用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;
}

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

这样,您应该能够从两个线程之间的示例编码中共享一个sim::Simulation实例。这将为共享对象/字段上的各种同步问题和种族打开门。因此,当您仅分享count时,请注意这一点,我认为这是一种原子可写的类型。