I'm using c++20's std::jthread (I'm actually using apple-clang 14.0 so I'm relying on Nicolai Josuttis' implementation).
In the program below I'm unable to join the default-constructed std::jthread thread with a thread.join() at the end of do_stuff() and the program fails with the following output:
Starting thread...
Max attempts exceeded.
libc++abi: terminating with uncaught exception of type std::__1::system_error: thread::join failed: Invalid argument
#include <fmt/core.h>
#include <thread>
class ThreadedProcessor {
private:
int attempt{0};
const int max_attempts = 1;
std::stop_source ssource;
std::jthread thread;
void do_stuff() {
while (attempt < max_attempts) {
++attempt;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
fmt::print("Max attempts exceeded.\n");
ssource.request_stop();
thread.join();
}
void start() { // was previously called process()
thread = std::jthread([&, stoken = ssource.get_token()]() {
fmt::print("Starting thread...\n");
while (!stoken.stop_requested()) {
do_stuff();
}
if (stoken.stop_requested()) {
fmt::print("Stop requested. Stopping thread.\n");
}
});
}
public:
ThreadedProcessor() {
process();
}
};
int main() {
auto tp = ThreadedProcessor();
}
How does one stop the thread properly in this case?