c++ - std::jthread 从另一个成员函数运行成员函数
问题描述
这是我的代码:
#include <iostream>
#include <zconf.h>
#include <thread>
class JT {
public:
std::jthread j1;
JT() {
j1 = std::jthread(&JT::init, this, std::stop_token());
}
void init(std::stop_token st={}) {
while (!st.stop_requested()) {
std::cout << "Hello" << std::endl;
sleep(1);
}
std::cout << "Bye" << std::endl;
}
};
void init_2(std::stop_token st = {}) {
while (!st.stop_requested()) {
std::cout << "Hello 2" << std::endl;
sleep(1);
}
std::cout << "Bye 2" << std::endl;
}
int main() {
std::cout << "Start" << std::endl;
JT *jt = new JT();
std::jthread j2(init_2);
sleep(5);
std::cout << "Finish" << std::endl;
}
这是输出:
Start
Hello
Hello 2
Hello
Hello 2
Hello
Hello 2
Hello
Hello 2
Hello
Hello 2
Finish
Bye 2
Hello
问题是我可以收到Bye 2
消息但不能收到Bye
消息。
我知道传递的stop_token
变量会导致这个问题,但我不知道如何将它传递给另一个成员函数内的成员函数。
解决方案
如果我正确地理解了这个问题(我的理解是std::jthread(&JT::init, this)
jthread 想要调用JT::init(std::stop_token st, this)
,这是行不通的),你可能想用std::bind_front
它来给它一个有效的 Callable。例如
JT() {
j1 = std::jthread(std::bind_front(&JT::init, this));
}
推荐阅读
- powershell - 无法运行位于远程 Azure VM D 中的远程 powershell 脚本:使用 Invoke-Command 的驱动器
- powershell - 从转换的 json 将成员添加到 pscustomobject 数组集合后无法更新值
- scala - 如何修复“错误:遇到不可恢复的循环解析导入”?
- macos - macOS/SwiftUI:使用 GraphicalDatePickerStyle() 时设置日期选择器的选择颜色/色调?
- kubernetes - 协调依赖对象 k8s 控制器运行时
- asp.net-mvc-5 - 在 ASP.NET MVC 5 中创建商店
- python-3.x - 用 None 替换 NaN 值填充 DataFrame 中前一行的值(pandas 1.0.3)
- javascript - 如何使用 MediaElementJS 和 Youtube 实现 VAST-ad?
- spring-boot - 提交n条记录后如何刷新
- python - 将实例字段作为参数传递