thread类是c++11的新特性。
特点:
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 后面的博客抽时间记录