繁体   English   中英

std::jthread 从另一个成员 function 运行成员 function

[英]std::jthread runs a member function from another member function

这是我的代码:

#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;
}

这是 output:

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变量会导致此问题,但我不知道如何将其传递给另一个成员 function 内的成员 function。

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

根据有用的评论,我重写了 class 代码如下:

class JT {
public:
    std::jthread j1;

    JT() {
        j1 = std::jthread(&JT::init, this);
    }

    void init() {
        auto st = j1.get_stop_token();
        while (!st.stop_requested()) {
            std::cout << "Hello" << std::endl;
            sleep(1);
        }
        std::cout << "Bye" << std::endl;
    }
};

您必须通过auto st = j1.get_stop_token();即时获取 stop_token .

以及修改后的主function:

int main() {
    std::cout << "Start" << std::endl;
    JT *jt = new JT();
//    auto jt = std::make_unique<JT>();
    std::jthread j2(init_2);
    sleep(5);
    std::cout << "Finish" << std::endl;
    delete jt;
}

您需要直接delete class object 或使用RAII (如智能指针)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM