C++20新线程 jthread 体验代码

// 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;
}
原文地址:https://www.cnblogs.com/aquester/p/13639020.html