簡體   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