#include <chrono>
#include <future>
#include <thread>
#include <cstdio>
struct Looper {
void loop() {
printf("\tloop....\n");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
};
struct LooperThread {
explicit LooperThread(Looper *looper) : mLooper(looper) {
mThreadId = std::this_thread::get_id();
}
void run() {
mThread = std::thread([this]() { this->threadLoop(this->mExitSignal.get_future()); });
mThread.detach();
}
void stop() { mExitSignal.set_value(); }
virtual ~LooperThread() {}
private:
Looper *mLooper;
std::thread::id mThreadId;
std::thread mThread;
std::promise<void> mExitSignal;
void threadLoop(std::future<void> exitListner) {
printf("start %s\n", __func__);
do {
mLooper->loop();
} while (exitListner.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout);
printf("exit %s\n", __func__);
}
};
int main() {
Looper looper;
LooperThread t{&looper};
t.run();
std::this_thread::sleep_for(std::chrono::seconds(5));
t.stop();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
输出
???@???:/local/mnt/workspace/practice/cpp$ ./out/main
start threadLoop
loop....
loop....
loop....
loop....
loop....
exit threadLoop
???@???:/local/mnt/workspace/practice/cpp$
Reference: https://thispointer.com/c11-how-to-stop-or-terminate-a-thread/