以下是关于 std::thread 的详细介绍,包括它的使用方法、特点以及一些常见的操作。
功能:创建并启动一个新线程。
语法:
std::thread::thread();
std::thread::thread(std::thread&& other); // 移动构造函数
template
//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);
功能:等待线程完成。
语法:
void join();
功能:检查线程是否可以被 join
。
语法:
bool joinable() const noexcept;
if (t.joinable()) {
t.join();
}
功能:分离线程,使其独立运行。
语法:
void detach();
this_thread 是C++11引入的命名空间,专门用于操作和管理当前线程。它提供了以下四个主要函数,用于线程控制和同步。
功能:获取线程的唯一标识符。
语法:
std::thread::id std::this_thread::get_id() const noexcept;
返回值:std::thread::id
类型的值,表示当前线程的ID。
#include
#include
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;
}
功能:使当前线程暂停执行指定的时间。
语法:
void sleep_for (const chrono::duration& rel_time);
std::chrono::time_point
类型,表示暂停的时间长度。#include
#include
#include
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;
}
功能:使当前线程暂停执行,直到指定的时间点。
语法:
void sleep_until (const chrono::time_point& abs_time);
std::chrono::time_point
类型,表示线程恢复执行的时间点。#include
#include
#include
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;
}
功能:让当前线程放弃当前的CPU时间片,允许其他线程运行。
语法:
void yield();
#include
#include
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;
}