简单记录一下多线程相关的 API
一 std::thread
std::thread
对象表示单个执行线程,通过给其传入一个任务函数来达到并发执行
1.构造函数
thread() noexcept;
// 默认构造函数,没有与之关联的执行线程
thread( thread&& other ) noexcept;
// 移动构造函数,移动后 other 不再表示执行线程
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
// 构造后执行线程开始执行,其中 f 为可调用对象,args为 f 的参数
thread( const thread& ) = delete;
// std::thread 只能移动,不能复制
std::thread 只能移动,不能复制
得到一个任务(函数)后立即创建线程并执行该任务
2.操作
void join();
// 阻塞当前线程直至 *this 所标识的线程结束其执行
void detach();
// 关联线程从 thread 对象分离,调用 detach 后 *this 不再占有这个关联线程。
void swap( std::thread& other ) noexcept;
// 交换两个 thread 对象的底层柄
3.观察器
bool joinable() const noexcept;
// thread 对象是否标识活跃的执行线程
// 默认构造的 thread 不可结合
// 结束执行代码,但仍未结合的线程仍被当作活跃的执行线程,从而可结合
// join() 和 detach() 后不可结合
std::thread::id get_id() const noexcept;
// 返回标识与 *this 关联的线程的 std::thread::id
4.std::thread 对象创建
(1)函数指针
void myFunction() {
// 执行的任务
}
int main() {
std::thread myThread(myFunction); // 使用函数指针创建线程
// ...
return 0;
}
(2)函数对象
struct MyFunctor {
void operator()() {
// 执行的任务
}
};
int main() {
MyFunctor functor;
std::thread myThread(functor)