在另一个线程中读取/写入信息
Read/Write information to class in another thread
也许我已经完全迷失了,但是我正在尝试学习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
时,请注意这一点,我认为这是一种原子可写的类型。
相关文章:
- 如何使用软化工具包从 OPC UA 服务器异步读取操作回调中的数据值响应中获取 NodeId 详细信息
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- Qt读取文本文件的一些信息
- 我正在尝试构建一个简单的程序来从 mysql 数据库中读取信息
- 从C 中读取书籍信息
- 在另一个线程中读取/写入信息
- 从一个二进制文件中读取信息,并写入另一个二进制文件
- 提升信息解析器在读取/写入 INFO 格式文件时删除所有注释
- (C++) 如何从要存储在结构数组中的二进制文件中读取.dat信息?
- 使用正则表达式从文件中读取数据信息
- 从结构化阵列中读取信息
- C ++,当我读取二进制文件时,我得到重复的信息
- 双击编译C++ Unix 可执行文件不会打开现有文件以从中读取信息
- C 读取文件,省略了一些信息
- 无法读取代码页不匹配的文件版本信息
- 如何从相机读取缓冲信息
- 通过将结构信息从二进制文件读取到数组中,然后返回到文件C
- 如何将信息从二进制数据文件读取到结构c 的数组中
- 如何从QT中的连接HID设备中读取信息
- 如何将文本文件中的信息读取到构造函数内部的动态数组中