hcnak.blog

posted at 2015-06-19 17:53:12 +0000

C++多线程编程

要用到的头文件 thread.h thread 是C++标准程序库中的一个头文件,定义了C++11标准中的一些表示线程的类 、用于互斥访问的类与方法等,位于std命名空间中。

thread对象表示一个线程。初始化时给出该线程的执行函数(或是可以调用的对象)。线程对象构造后即开始运行。默认情况下,C++11的子线程必须与主线程会合,即在主线程中调用thread::join()函数。这避免了如此情形:子线程还在执行,主线程已经执行结束而撤销。

一些方法及说明:

 //构造函数:
template explicit thread (Fn&& fn, Args&&... args); //这是最常用的构造函数,将要执行的函数作为第一个参数传入,它的参数则作为构造函数2−>n个参数传入 

//成员函数:
thread::hardware_concurrency();  //静态成员函数,返回当前计算机最大的硬件并发线程数目。
thread::get_id();        //返回线程对象的id  
thread::joinable();     //检查线程是否可被加入主线程  
thread::join();          //将线程加入主线程
thread::detach();      //将线程从主线程中分离

首先,我们要创建thead对象,并将要执行的函数及参数传入,

std::thread thd_a(ShowMsgA,"线程一执行中。。。");

然后继续执行程序其它部分,但一定要将子线程加入主线程

thd_a.join();

完整代码如下:

# include<iostream>
# include<thrad>

//线程函数 
void ShowMsgA(const std::string & msg) { 
  while (true) { 
    std::cout << msg << std::endl; 
  }
}

void ShowMsgB(const std::string & msg) { 
  while (true) { 
    std::cout << msg << std::endl; 
  }
}

void ShowMsgC(const std::string & msg) { 
  while (true) { 
    std::cout << msg << std::endl; 
  }
}

//主函数 
int main(int argc, char * argv) { 
  std::cout << "这个程序演示了C++多线程rn创建3个线程"<<std::endl; //创建3个线程 
  std::thread thd_a(ShowMsgA,"线程一执行中。。。"); 
  std::thread thd_b(ShowMsgB, "线程2执行中。。。"); 
  std::thread thd_c(ShowMsgC, "线程三执行中。。。");

  std::cout << "则是主线程" << std::endl;

  //加入主线程,避免主线程自行完毕后,子线程还在
  thd_a.join();
  thd_b.join();
  thd_c.join();

  std::cin.get();
  return 0;

}


© kanchzl AT kanchz DOT com

last updated on 2022-07-27 01:57:54 +0000