7eR*_*RoM 3 c++ multithreading class
这是我的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
Start
Hello
Hello 2
Hello
Hello 2
Hello
Hello 2
Hello
Hello 2
Hello
Hello 2
Finish
Bye 2
Hello
Run Code Online (Sandbox Code Playgroud)
问题是我可以收到Bye 2消息但收不到Bye消息。
我知道传递的stop_token变量会导致此问题,但我不知道如何将其传递给另一个成员函数内的成员函数。
Has*_*kun 11
如果我正确地理解了这个问题(我的理解是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));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2052 次 |
| 最近记录: |