在C++中,std::thread 是C++11引入的线程库的一部分,用于创建和管理线程。它提供了一个简单而强大的方式来实现多线程编程。
thread库底层是对各个系统的线程库进⾏封装,如Linux下的pthread库和Windows下Thread库等,所以C++11 thread库的第⼀个特点是可以跨平台,第⼆个特点是Linux和Windows下提供的线程库都是⾯向过程的,C++11 thread是库⾯向对象的,并且融合了⼀些C++11语⾔特点,如右值引⽤的移动语义,可变模板参数等,⽤起来会更好⽤⼀些。
以下是关于 std::thread 的详细介绍,包括它的使用方法、特点以及一些常见的操作。
创建线程
构造函数
-
功能:创建并启动一个新线程。
-
语法:
std::thread::thread();
std::thread::thread(std::thread&& other); // 移动构造函数
template <class F, class... Args>
//F 为函数指针或lambda表达式等函数对象,Args 为函数F所需的参数
std::thread::thread(F&& f, Args&&... args);
auto Sum = [](int n) {
int ret = 0;
for (int i = 1; i <= n; i++)
{
ret += i;
}
cout << ret << endl;
};
//直接构造
thread t1(Sum, 10);
//移动构造
thread t2;
t2 = thread(Sum, 20);
join
-
功能:等待线程完成。
-
语法:
void join();
joinable
-
功能:检查线程是否可以被
join
。 -
语法:
bool joinable() const noexcept;
if (t.joinable()) {
t.join();
}
detach
-
功能:分离线程,使其独立运行。
-
语法:
void detach();
使用 this_thread 管理线程
this_thread 是C++11引入的命名空间,专门用于操作和管理当前线程。它提供了以下四个主要函数,用于线程控制和同步。
get_id
-
功能:获取线程的唯一标识符。
-
语法:
std::thread::id std::this_thread::get_id() const noexcept;
-
返回值:
std::thread::id
类型的值,表示当前线程的ID。
#include<iostream>
#include<thread>
using namespace std;
int main()
{
auto Print = [](string name) {
thread::id id= this_thread::get_id();
cout << "线程 "<< name << " 的ID: "<< id << endl;
};
//直接构造
thread t1(Print, "t1");
t1.join();
//移动构造
thread t2;
t2 = thread(Print, "t2");
t2.join();
return 0;
}
sleep_for
-
功能:使当前线程暂停执行指定的时间。
-
语法:
void sleep_for (const chrono::duration<Rep,Period>& rel_time);
- 参数:
std::chrono::time_point
类型,表示暂停的时间长度。
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void func() {
for (int i = 1; i <= 3; i++) {
cout << "子线程休眠 " << i << " 秒..." << endl;
this_thread::sleep_for(chrono::seconds(1));
}
}
int main() {
thread t1(func);
t1.join();
return 0;
}
sleep_until
-
功能:使当前线程暂停执行,直到指定的时间点。
-
语法:
void sleep_until (const chrono::time_point<Clock,Duration>& abs_time);
- 参数:
std::chrono::time_point
类型,表示线程恢复执行的时间点。
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main() {
auto now = chrono::system_clock::now();
auto future_time = now + chrono::seconds(5);
cout << "主线程将在 5 秒后继续执行..." << endl;
this_thread::sleep_until(future_time);
cout << "主线程恢复执行。" << endl;
}
yield
-
功能:让当前线程放弃当前的CPU时间片,允许其他线程运行。
-
语法:
void yield();
#include <iostream>
#include <thread>
using namespace std;
void func() {
for (int i = 0; i < 3; ++i) {
cout << "子线程执行中,主动让出 CPU..." << endl;
this_thread::yield();
}
}
int main() {
thread t1(func);
t1.join();
return 0;
}