首页 > 解决方案 > 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变量会导致这个问题,但我不知道如何将它传递给另一个成员函数内的成员函数。

标签: c++multithreadingclass

解决方案


如果我正确地理解了这个问题(我的理解是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));
}

推荐阅读