• c++的多线程和多进程


    一、多进程和多线程对比

    多进程:进程不止一个,开销比较大,通信方式比较复杂(可以用过管道、文件、消息队列进行通信),维护成本不高。

    多线程:利用共享内存的方式进行指令的执行,开销比较低,但是维护起来比较麻烦,需要考虑到共享资源的问题。不支持分布式运算。

    二、多线程举例

    #include "iostream.h"
    #include "thread.h"
    using namespace std;
    
    void function()
    {
     cout<<"hello world"<<end;
    }
    
    int main()
    {
      std::thread t(function); //t()内为要在此线程执行的方法
      t.join();                       //t加入主线程,主线程等待他执行完毕再执行
      //t.detach();                //并发执行,和主线程同时执行,可能导致主线程执行完毕它                                 // 没有机会执行,并且被detach的不能在join,除非加判断入下
    
    /* if(t.joinable())
    {
       t.join();
    }*/
    
    
     
      return null;
    }

    三、多线程管理

    1、

    void function()
    {
      for(int i=0,i<10;i++)
     {
      cout<<"form t,i love u";
     }
    }
    
    int main()
    {
     thread t((function()));//线程执行的另一种方式
    try
    {
      for(int i=0,i<10;i++)
     {
      cout<<"form main,i love u";
     }
    }
    catch(...)
    {
    t.join();
    throw;  //保证t和main有一个执行
    }
    
    }

    2、线程只能被move而不能被复制,线程可以执行一切可以被调用的结构(包括类等)

    calss factor
    {
    void function(string str)
    {
    
     cout<<"hello"+str<<endl;
    }
    }
    
    
    void main()
    
    {
    string s="u";
    thread t((function()),s);
    
    
    }
    
    如果是通过引用传递参数;
    calss factor
    {
    void function(string& str)
    {
    
     cout<<"hello"+str<<endl;
    }
    }
    相应的调用部分应该是:
    thread t((function()),std::ref(s));
    如果调用的时候是:
    thread t((function()),s);
    尽管被调用的方法是引用传递值的,但是并不会影响值传递之实;
    引用就是别名的概念,可以减少不必要的复制;
    
    引用还可以写成
    thread t((function()),move(s));
    但是线程只能写成move
    如:
    thread t2=move(t);

    3、每个线程具有唯一的线程Id,可以用get_id()获取;

    4、每个任务可以用多少个线程高效完成操作,和cpu的核心数有关,过多反而会导致效率低;

    thread::hardware_concurrency() 查看最多多少比较合适

  • 相关阅读:
    时间比较
    syslog 协议及其在 SysLogHandler 中的使用
    获取 postgresql 的当前索引
    dns域名解析
    wireshark
    ctypes使用
    python模块signal
    ThreadPoolExecutor多线程异步执行
    异步进程 multiprocessing 模板
    redis常见错误
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/6181419.html
Copyright © 2020-2023  润新知