Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::jthread runs a member function from another member function

Here is my code:

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

Here is the output:

Start
Hello
Hello 2
Hello
Hello 2
Hello
Hello 2
Hello
Hello 2
Hello
Hello 2
Finish
Bye 2
Hello

The problem is I could get Bye 2 message but not Bye message.

I know the passed stop_token variable results in this problem but I do not know how to pass it to a member function inside another member function.

like image 257
7eRoM Avatar asked Oct 23 '25 11:10

7eRoM


1 Answers

If I'm understanding the problem correctly (my understanding being that for std::jthread(&JT::init, this) jthread wants to call JT::init(std::stop_token st, this), which isn't going to work), you probably want to use std::bind_front to give it a Callable that works. e.g.

    JT() {
    j1 = std::jthread(std::bind_front(&JT::init, this));
}
like image 156
Hasturkun Avatar answered Oct 26 '25 01:10

Hasturkun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!