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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值