Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to start a new jthread on a class member

I think the question is quite obvious. The I have tried so far:

#include <thread>
#include <chrono>

using namespace std::literals::chrono_literals;

class test
{
public:
    void member(std::stop_token stoken)
    {
        std::this_thread::sleep_for(1s);
    }

    void run()
    {
        // None compiles correctly
        // std::jthread jt(&member);
        // std::jthread jt(&test::member, this);
    }
};

int main()
{
    test t;
    t.run();

    return 0;
}

Is it possible with the new jthread & with using stop_token?
Ps.: Of course it’s possible to workaround it by making the member function static or by removing the stop_token. But I’m curious if there’s a real & clean solution instead of extra N lines of hacking.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use std::bind_front to bind this to &test::member and pass it to jthread:

#include <thread>
#include <chrono>
#include <functional>

using namespace std::literals::chrono_literals;
class test
{
public:
    void member(std::stop_token stoken)
    {
        std::this_thread::sleep_for(1s);
    }

    void run()
    {
        std::jthread jt(std::bind_front(&test::member, this));
    }
};

int main()
{
    test t;
    t.run();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading