【c++】线程thread类
2016-07-13 19:44
423 查看
thread类是c++11的新特性。
特点:
std::thread 使用函数作为参数,同时可以为函数接受参数,数目不定。
std::thread 和其他的 std 类一样,主要是提供给我们使用,而不是供我们继承。
std::thread的第一个参数是线程函数名,后面的参数是传给线程函数的参数,当一个std::thread对象被创建后(默认状态下joinable),在对象被析构前必须调用其成员函数join()来等待线程执行结束并释放资源 或者 调用其成员函数detach()将线程分离(独立),此时线程执行完后会自己释放资源。
使用范例:(file: main1.cpp)
gcc(版本5.3.1)编译,添加 -std=c++11 以及 -lpthread
执行结果:
(本例子也是对博客 【c++】lambda表达式 例子的补充。)
std::thread还有其他成员函数:
get_id :获取线程ID
joinable:检查线程是否可被join
join:join线程
detach:Detach线程
swap:Swap线程
nativa_handle:返回 native handle。
hadrware_concurrency[static]:检测硬件并发特性
跟std::thread经常搭配使用的还有std::mutex,std::lock_guard 后面的博客抽时间记录
特点:
std::thread 使用函数作为参数,同时可以为函数接受参数,数目不定。
std::thread 和其他的 std 类一样,主要是提供给我们使用,而不是供我们继承。
std::thread的第一个参数是线程函数名,后面的参数是传给线程函数的参数,当一个std::thread对象被创建后(默认状态下joinable),在对象被析构前必须调用其成员函数join()来等待线程执行结束并释放资源 或者 调用其成员函数detach()将线程分离(独立),此时线程执行完后会自己释放资源。
使用范例:(file: main1.cpp)
/*********************************** author:arvik email:1216601195@qq.com csdn:http://blog.csdn.net/u012819339 ************************************/ #include <iostream> #include <thread> #include <string> using namespace std; class init { public: void hello(void) const {cout<<"hello"<<endl;} void hello(string str) const {cout<<"hello,"<<str<<endl;} void hello(int i, string str) const { while(i--) { cout<<i<<": "; this->hello(str); } } }; void fun(int a, char b) { while(a--) { cout<<a<<": only hello!, b:"<<b<<endl; } } int main() { init myin; string mystr = "world"; thread th([myin, mystr](){myin.hello(4, mystr);}); th.detach(); cout<<"====================="<<endl; thread *mypt = new thread(fun, 2, 't'); mypt->join(); delete mypt; return 0; }
gcc(版本5.3.1)编译,添加 -std=c++11 以及 -lpthread
c++ -o t1 main1.cpp -std=c++11 -lpthread
执行结果:
===================== 1: only hello!, b:t 0: only hello!, b:t 3: hello,world 2: hello,world 1: hello,world 0: hello,world
(本例子也是对博客 【c++】lambda表达式 例子的补充。)
std::thread还有其他成员函数:
get_id :获取线程ID
joinable:检查线程是否可被join
join:join线程
detach:Detach线程
swap:Swap线程
nativa_handle:返回 native handle。
hadrware_concurrency[static]:检测硬件并发特性
跟std::thread经常搭配使用的还有std::mutex,std::lock_guard 后面的博客抽时间记录
相关文章推荐
- NYOJ 大数阶乘问题
- c++11多线程 互斥量
- C++ 创建动态二维数组
- C/C++语言参数传递----值传递、引用传递、指针传递、指针引用传递
- java的数据类型与c语言的区别
- 图解VC++版PE文件解析器源码分析
- 136. Single Number
- C++11 long long使用及输出
- boost静态链接库和c++/clr不兼容问题:未能加载文件或程序集,不是有效的Win32应用程序。
- LeetCode:Implement strStr()
- C++中的对齐方式及sizeof小结
- C/C++语言中#的神奇作用:把宏参数字符串化/贴合宏参数
- UE4学习笔记(三): 为什么使用C++替代UnrealScript?
- 收集的C/C++执行外部程序(调用外部exe程序)文章
- stringstream string转换成long型遇到的问题
- Leetcode 231. Power of Two (Easy) (cpp)
- 浅谈C语言中"#ifndef/#define/#endif"的作用
- (C++)UNION结构
- 常用算法题目3道
- 浅析长度为0的数组