目录
一、简单使用
C++11提供了一套精练的线程库,小巧且易用。运行一个线程,可以直接创建一个std::thread的实例,线程在实例成功构造成时启动。若有底层平台支持,成员函数std::thread::native_handle()将可提供对原生线程对象运行平台特定的操作。
#include <thread>
#include <iostream>
void foo() {
std::cout << "Hello C++11" << std::endl;
}
int main() {
std::thread thread(foo); // 启动线程foo
thread.join(); // 等待线程执行完成
return 0;
}
编译并运行,程序输出:
Hello C++11
1、线程参数
当需要向线程传递参数时,可以直接通过std::thread的构造函数参数进行,构造函数通过完美转发将参数传递给线程函数。
#include <thread>
#include <iostream>
void hello(const char *name) {
std::cout << "Hello " << name << std::endl;
}
int main() {
std::thread thread(hello, "C++11");
thread.join();
return 0;
}
2. 类成员函数做为线程入口
类成员函数做为线程入口时,仍然十分简单: 把this做为第一个参数传递进去即可。
#include <thread>
#include <iostream>
class Greet
{
const char *owner = "Greet";
public:
void SayHello(const char *name) {
std::cout << "Hello " << name << " from " << this->owner << std::endl;
}
};
int main() {
Greet greet;
std::thread thread(&Greet::SayHello, &greet, "C++11");
thread.join();
return 0;
}
//输出:Hello C++11 from Greet
3. join: 等待线程执行完成
线程如果像二哈似的撒手没,则程序铁定悲剧。因此std::thread提供了几个线程管理的工具,其中join就是很重要的一个:等待线程执行完成。即使当线程函数已经执行完成后,调用join仍然是有效的。
4. 线程暂停
从外部让线程暂停,会引发很多并发问题。大家可以百度一下,此处不做引申。这大概也是std::thread并没有直接提供pause函数的原因。但有时线程在运行时,确实需要“停顿”一段时间怎么办呢?可以使用std::this_thread::sleep_for或std::this_thread::sleep_until
#include <thread>
#include <iostream>
#include <chrono>
using namespace st