zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    集群间如何实现session共享
    详解PHP如何实现单点登录
    jsonp原理详解
    跨站请求CSRF攻击
    防止SQL注入
    在springboot中使用h2数据库
    Datalab实验
    飞步无人驾驶2018届校园招聘在线笔试A轮
    HDU6030 Happy Necklace
    HDU5950 Recursive sequence
  • 原文地址:https://www.cnblogs.com/aquester/p/13639020.html
Copyright © 2011-2022 走看看