岚天逸见

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

posted on   岚天逸见  阅读(895)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2018-09-09 Linux远程批量工具mooon_ssh和mooon_upload使用示例
2018-09-09 Kafka常用命令收录
2018-09-09 Redis-4.0.11集群配置
2018-09-09 大压力下Redis参数调整要点

导航

统计信息

点击右上角即可分享
微信分享提示