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

     

  • 相关阅读:
    Log4net使用指南[转]
    SQL 数据库全库检索
    10款屏幕取色器/颜色拾取工具软件介绍及下载地址[转]
    字符串加密解密函数 (C#) (转)
    C# 读写文本文件乱码解决方案
    C# tips 设置文本框光标的位置[转]
    如何显示数据库中的试题和图形[转]
    [转帖]C#执行SQL脚本,读取XML文件
    使用AnimateWindow API函数实现动画窗体
    雨林木风 Ylmf Linux Y1.5(Ubuntu 9.10)正式发布[转]
  • 原文地址:https://www.cnblogs.com/hebust-fengyu/p/12077200.html
Copyright © 2011-2022 走看看