C++11 的新特性: thread

来源:互联网 发布:淘宝怎么判断虚假交易 编辑:程序博客网 时间:2024/04/27 20:14

这篇博客说的比较全面:

http://blog.csdn.net/tujiaw/article/details/8245130


我这里只贴一下我用到的部分内容:


windows系统中,需要vs2012才支持。


1.线程的创建
C++11线程类std::thread,头文件include <thread>
首先,看一个最简单的例子:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. void my_thread()  
  2. {  
  3.     puts("hello, world");  
  4. }  
  5.   
  6. int main(int argc, char *argv[])  
  7. {  
  8.     std::thread t(my_thread);  
  9.     t.join();  
  10.   
  11.     system("pause");  
  12.     return 0;  
  13. }  

实例化一个线程对象t,参数my_thread是一个函数,在线程创建完成后将被执行,
t.join()等待子线程my_thread执行完之后,主线程才可以继续执行下去,此时主线程会
释放掉执行完后的子线程资源。


当然,如果不想等待子线程,可以在主线程里面执行t.detach()将子线程从主线程里分离,
子线程执行完成后会自己释放掉资源。分离后的线程,主线程将对它没有控制权了。
相对于以前使用过的beginthread传多个参数需要传入struct地址,
boost::thread传参需要bind,std::thread传参真的非常方便,而且可读性也很好。
下面例子在实例化线程对象的时候,在线程函数my_thread后面紧接着传入两个参数。
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include <stdlib.h>  
  3. #include <thread>  
  4. #include <string>  
  5.   
  6. void my_thread(int num, const std::string& str)  
  7. {  
  8.     std::cout << "num:" << num << ",name:" << str << std::endl;  
  9. }  
  10.   
  11. int main(int argc, char *argv[])  
  12. {  
  13.     int num = 1234;  
  14.     std::string str = "tujiaw";  
  15.     std::thread t(my_thread, num, str);  
  16.     t.detach();  
  17.       
  18.     system("pause");  
  19.     return 0;  
  20. }  

0 0
原创粉丝点击