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个左右。

     

  • 相关阅读:
    (Good Bye 2019) Codeforces 1270B Interesting Subarray
    (Good Bye 2019) Codeforces 1270A Card Game
    Codeforces 1283D Christmas Trees(BFS)
    Codeforces 1283C Friends and Gifts
    Codeforces 1283B Candies Division
    1095 Cars on Campus (30)
    1080 Graduate Admission (30)
    1099 Build A Binary Search Tree (30)
    1018 Public Bike Management (30)
    1087 All Roads Lead to Rome (30)
  • 原文地址:https://www.cnblogs.com/hebust-fengyu/p/12077200.html
Copyright © 2011-2022 走看看