// C++20新線程 jthread 體驗代碼
//
// 編譯(編譯本代碼,-pedantic 不是必須的):
// g++ -std=c++20 -Wall -pedantic -pthread -static-libstdc++ C++20_jthread.cpp -o C++20_jthread
//
// 要求GCC10及以上版本,
// 可使用GCC的Docker鏡像靜態鏈接stdc++庫,以方便在非GCC10環境運行。
//
// docker pull gcc
// docker run --rm -it -v /data:/data gcc
#include <chrono>
//#include <coroutine> // -fcoroutines
#include <iostream>
#include <stdexcept>
#include <thread>
// 線程執行體
void thread_proc(std::stop_token st)
{
// 以往中,
// 需要自己實現 stop 來停止線程,
// 現在 jthread 內置了此能力。
while (!st.stop_requested())
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Thread " << std::this_thread::get_id() << " exit" << std::endl;
}
extern "C"
int main()
{
std::jthread thr(&thread_proc); // 創建線程
std::this_thread::sleep_for(std::chrono::seconds(10));
thr.request_stop(); // 通知線程退出
thr.join();
return 0;
}