• std::thread(2)


    个线程都有一个唯一的 ID 以识别不同的线程,std:thread 类有一个 get_id() 方法返回对应线程的唯一编号,你可以通过 std::this_thread 来访问当前线程实例,下面的例子演示如何使用这个 id:
    #include <thread>
    #include <iostream>
    #include <vector>
     
    void hello(){
        std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
    }
     
    int main(){
        std::vector<std::thread> threads;
     
        for(int i = 0; i < 5; ++i){
            threads.push_back(std::thread(hello));
        }
     
        for(auto& thread : threads){
            thread.join();
        }
     
        return 0;
    }
    依次启动每个线程,然后把它们保存到一个 vector 容器中,程序执行结果是不可预测的,例如:
    
    Hello from thread 140276650997504
    Hello from thread 140276667782912
    Hello from thread 140276659390208
    Hello from thread 140276642604800
    Hello from thread 140276676175616
    
    也可能是:
    
    Hello from thread Hello from thread Hello from thread 139810974787328Hello from thread 139810983180032Hello from thread
    139810966394624
    139810991572736
    139810958001920
    
    或者其他结果,因为多个线程的执行是交错的。你完全没有办法去控制线程的执行顺序(否则那还要线程干吗?)
    使用 lambda 启动线程
    当线程要执行的代码就一点点,你没必要专门为之创建一个函数,你可以使用 lambda 来定义要执行的代码,因此第一个例子我们可以改写为:
    #include <thread>
    #include <iostream>
    #include <vector>
     
    int main(){
        std::vector<std::thread> threads;
     
        for(int i = 0; i < 5; ++i){
            threads.push_back(std::thread([](){
                std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
            }));
        }
     
        for(auto& thread : threads){
            thread.join();
        }
     
        return 0;
    }
    在这里我们使用了一个 lambda 表达式替换函数指针,而结果是一样的。
  • 相关阅读:
    centos下安装chrome
    【CRT】设置 ip 显示和标签动作
    【IDEA】修改自动提示框的颜色
    【IDEA】monikai 主题
    【snmp】snmpwalk 指定端口
    【多对多】多对多取数无序的问题
    【百度搜索】屏蔽广告,高效搜索
    mybatis报错:Cause: java.io.FileNotFoundException: http://commons.apache.org/dtds/mbeans-descriptors.dtd
    怎么让request inputstream 可以多次读取
    win10下git bash console中文乱码
  • 原文地址:https://www.cnblogs.com/zzyoucan/p/3704135.html
Copyright © 2020-2023  润新知