zoukankan      html  css  js  c++  java
  • 第2章 管理线程

    2.1 基本线程管理

    1. 不等待线程完成的启动方式

    #include<iostream>
    #include<thread>
    #include<cstring>
    
    using namespace std;
    
    
    void print(){
        cout << "hello world" << endl;
    }
    
    
    int main(){
    
        thread t(print);
        t.detach();
        
        return 0;
    }
    
    //------运行结果------------
    /*
    PS E:Desktop> g++ -std=c++11 .1.cpp
    PS E:Desktop> a
    PS E:Desktop>
    */
    

      该方法中的启动线程方式UNIX中的守护线程相似,都是被分离的线程(参照UNIX的守护线程的概念,被分离的线程通常被称为守护线程)。

    2. 等待线程的完成的方式

    #include<iostream>
    #include<thread>
    #include<cstring>
    
    using namespace std;
    
    
    void print(){
        cout << "hello world" << endl;
    }
    
    
    int main(){
    
        thread t(print);
        if(t.joinable())
            t.join();
        
        return 0;
    }
    
    
    
    //----------------运行结果-------------------
    /*
    
    PS E:Desktop> g++ -std=c++11 .1.cpp
    PS E:Desktop> a
    hello world
    
    */

    2.2 传递参数给线程函数

    #include<iostream>
    #include<thread>
    #include<cstring>
    
    using namespace std;
    
    
    void print(string s){
        cout << s << endl;
    }
    
    
    int main(){
        thread t(print, "hello world");
        if(t.joinable()) 
            t.join();
        
        return 0;
    }
    

      在进行参数传递的时候可以在构造的thread对象中进行传递。

    2.3 转移对象所有权

    thread对象也可以像普通对象一样使用 t1 = std::mvoe(t),的形式进行所有权的转让。

    2.4 在运行时选择线程数量

    由于线程的切换是要消耗资源的所以在使用多线程进行并发编程时要考虑硬件线程数,如果处理器只支持一个线程,我们的代码中开启了多个线程,这样在进行切线程时,也会表白浪费掉很多时间,所以我们可以根据thread::hardware_concurrency()来获取线程的数量。

    #include<iostream>
    #include<thread>
    #include<cstring>
    
    using namespace std;
    
    
    int main(){
        cout << thread::hardware_concurrency() << endl;
        
        return 0;
    }
    //------------运行结果------
    /*
    PS E:Desktop> g++ -std=c++11 .1.cpp
    PS E:Desktop> a
    4
    */
    

      可以发现我的电脑中是支持4个线程的,所以在开启多线程数量的时候,尽量选择4个左右。

     

  • 相关阅读:
    Android消息机制(Handler)详述
    Android自定义组件-以饼状图并实现点击事件为例
    Markdown中tab的解析与4个空格 问题
    策略模式(Strategy)
    观察者模式(Observer)
    适配器模式(Adapter Class/Object)
    建造者模式(Builder)
    简单工厂模式、工厂方法模式、抽象工厂模式
    单例模式(Singleton)
    工具推荐:前后端一体化部署,效能提升开源“神器”
  • 原文地址:https://www.cnblogs.com/hebust-fengyu/p/12077200.html
Copyright © 2011-2022 走看看