c++ - C++ 在单独的线程中调用类方法
问题描述
比如说,我有一个有两种方法的类:一个主线程和一个单独的线程。
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
class Foo
{
bool is_ready;
public:
Foo()
{
is_ready = false;
}
void async_func()
{
this_thread::sleep_for(chrono::milliseconds(2000)); // do some long stuff
is_ready = true;
}
void main_thread_func()
{
thread t([&] (Foo* foo) { foo->async_func(); }, this);
t.join();
while(true)
{
cout << is_ready << endl;
this_thread::sleep_for(chrono::milliseconds(100));
}
}
};
int main()
{
Foo foo;
foo.main_thread_func();
return 0;
}
我想查看一条状态为“is_ready”的消息,以了解另一个线程函数的进度。实际上,只有当它变为“真实”时,我才能看到消息。
函数停止时如何查看所有未等待的进度?
解决方案
您之前调用了 join 函数,因此主线程正在等待完成创建的线程。你应该在正确的地方调用 join 函数,例如在 while(true) 之后。
推荐阅读
- docker - Ubuntu Docker 映像标签与 Ubuntu 发行版次要编号
- javascript - 每 X 分钟更新一次 nodejs scraper json
- ms-access - 女士访问选择语句未检索
- r - 创建 AICc 表但不断收到 aictab 错误:找不到函数
- terraform - Terraform:迭代至少一个没有特殊属性的对象
- excel - 如何从查询中获取上次刷新日期/时间?
- go - 检查 js.Value 是否存在
- python - Beautifulsoup 返回错误的 href 值
- python-3.x - Kivy 按钮不显示
- html - 通过点击红宝石中的按钮触发功能