首页 > 编程 > C++ > 正文

C++程序中启动线程的方法

2020-05-23 14:18:38
字体:
来源:转载
供稿:网友

这篇文章主要介绍了C++程序中启动线程的方法,作者针对C++11版本中的一些新特性进行了解说,需要的朋友可以参考下

C++11 引入一个全新的线程库,包含启动和管理线程的工具,提供了同步(互斥、锁和原子变量)的方法,我将试图为你介绍这个全新的线程库。

如果你要编译本文中的代码,你至少需要一个支持 C++11 的编译器,我使用的是 GCC 4.6.1,需要使用 -c++0x 或者 -c++11 参数来启用 C++11 的支持。

启动线程

在 C++11 中启动一个线程是非常简单的,你可以使用 std:thread 来创建一个线程实例,创建完会自动启动,只需要给它传递一个要执行函数的指针即可,请看下面这个 Hello world 代码:

 

 
  1. #include <thread> 
  2. #include <iostream> 
  3.  
  4. void hello(){ 
  5. std::cout << "Hello from thread " << std::endl; 
  6.  
  7. int main(){ 
  8. std::thread t1(hello); 
  9. t1.join(); 
  10.  
  11. return 0; 

所有跟线程相关的方法都在 thread 这个头文件中定义,比较有意思的是我们在上面的代码调用了 join() 函数,其目的是强迫主线程等待线程执行结束后才退出。如果你没写 join() 这行代码,可能执行的结果是打印了 Hello from thread 和一个新行,也可能没有新行。因为主线程可能在线程执行完毕之前就返回了。

线程标识

每个线程都有一个唯一的 ID 以识别不同的线程,std:thread 类有一个 get_id() 方法返回对应线程的唯一编号,你可以通过 std::this_thread 来访问当前线程实例,下面的例子演示如何使用这个 id:

 

 
  1. #include <thread> 
  2. #include <iostream> 
  3. #include <vector> 
  4.  
  5. void hello(){ 
  6. std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl; 
  7.  
  8. int main(){ 
  9. std::vector<std::thread> threads; 
  10.  
  11. for(int i = 0; i < 5; ++i){ 
  12. threads.push_back(std::thread(hello)); 
  13.  
  14. for(auto& thread : threads){ 
  15. thread.join(); 
  16.  
  17. return 0; 

依次启动每个线程,然后把它们保存到一个 vector 容器中,程序执行结果是不可预测的,例如:

 

 
  1. Hello from thread 140276650997504 
  2. Hello from thread 140276667782912 
  3. Hello from thread 140276659390208 
  4. Hello from thread 140276642604800 
  5. Hello from thread 140276676175616 

也可能是:

 

 
  1. Hello from thread Hello from thread Hello from thread 139810974787328Hello from thread 139810983180032Hello from thread 
  2. 139810966394624 
  3. 139810991572736 
  4. 139810958001920 

或者其他结果,因为多个线程的执行是交错的。你完全没有办法去控制线程的执行顺序(否则那还要线程干吗?)

当线程要执行的代码就一点点,你没必要专门为之创建一个函数,你可以使用 lambda 来定义要执行的代码,因此第一个例子我们可以改写为:

 

 
  1. #include <thread> 
  2. #include <iostream> 
  3. #include <vector> 
  4.  
  5. int main(){ 
  6. std::vector<std::thread> threads; 
  7.  
  8. for(int i = 0; i < 5; ++i){ 
  9. threads.push_back(std::thread([](){ 
  10. std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl; 
  11. })); 
  12.  
  13. for(auto& thread : threads){ 
  14. thread.join(); 
  15.  
  16. return 0; 

在这里我们使用了一个 lambda 表达式替换函数指针,而结果是一样的。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表