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.
CodePudding user response:
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();
}