背景
运行一个可执行程序会产生成一个进程,同时该进程所属的主线程开始自动运行;主线程从 main() 函数开始执行,当 main() 函数返回,则整个进程执行完毕。
当我们创建自己的线程时,也需要从一个函数开始执行;若该函数执行完毕,则线程结束。
std::thread
在 C++11中新引入了线程库 std::thread ,用于创建线程,包含在头文件 #include 中 。
①.std::thread 对象只具有移动属性,不具备拷贝属性,其拷贝构造、拷贝赋值函数是 delete 的。
②.每个线程都具有唯一的 id,使用数字表示。可使用函数 std::this_thread::get_id() 来获取当前线程的 id,也可以通过 std::thread 对象的成员函数 get_id() 来获取。
代码示例
本质上创建 std::thread对象需要传入一个可调用对象,可以由以下几种方式:
①.使用普通函数创建线程
#include "thread"
#include "iostream"
using namespace std;
void functionToThread()
{
cout << "线程启动......" << endl;
cout << "线程结束......" << endl;
}
int main()
{
thread myThread(functionToThread);
system("pause");
return 0;
}
②.使用 lambda 表达式创建线程
#include "thread"
#include "iostream"
using namespace std;
int main()
{
auto lambdaThread = [](){
cout << "线程启动......" << endl;
cout << "线程结束......" << endl;
};
thread myThread(lambdaThread);
system("pause");
return 0;
}
③.使用类对象创建线程
#include "thread"
#include "iostream"
using namespace std;
class classDemo
{
public:
void operator()()
{
cout << "线程启动......" << endl;
cout << "线程结束......" << endl;
}
};
int main()
{
classDemo demo;
thread myThread(demo);
system("pause");
return 0;
}
④.使用类的成员函数创建线程
#include "thread"
#include "iostream"
using namespace std;
class classDemo
{
public:
void functionToThread()
{
cout << "线程启动......" << endl;
cout << "线程结束......" << endl;
}
};
int main()
{
classDemo demo;
thread myThread(&classDemo::functionToThread,&demo);
//使用bind
thread mymyThread1(bind(&classDemo::functionToThread, &demo));
//使用mem_fn
thread mymyThread2(mem_fn(&classDemo::functionToThread), &demo);
system("pause");
return 0;
}