std::thread(2)

时间:2024-01-02 19:58:35
个线程都有一个唯一的 ID 以识别不同的线程,std:thread 类有一个 get_id() 方法返回对应线程的唯一编号,你可以通过 std::this_thread 来访问当前线程实例,下面的例子演示如何使用这个 id:
#include <thread>
#include <iostream>
#include <vector> void hello(){
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
} int main(){
std::vector<std::thread> threads; for(int i = ; i < ; ++i){
threads.push_back(std::thread(hello));
} for(auto& thread : threads){
thread.join();
} return ;
}
依次启动每个线程,然后把它们保存到一个 vector 容器中,程序执行结果是不可预测的,例如: Hello from thread
Hello from thread
Hello from thread
Hello from thread
Hello from thread 也可能是: Hello from thread Hello from thread Hello from thread 139810974787328Hello from thread 139810983180032Hello from thread 或者其他结果,因为多个线程的执行是交错的。你完全没有办法去控制线程的执行顺序(否则那还要线程干吗?)
使用 lambda 启动线程
当线程要执行的代码就一点点,你没必要专门为之创建一个函数,你可以使用 lambda 来定义要执行的代码,因此第一个例子我们可以改写为:
#include <thread>
#include <iostream>
#include <vector> int main(){
std::vector<std::thread> threads; for(int i = ; i < ; ++i){
threads.push_back(std::thread([](){
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}));
} for(auto& thread : threads){
thread.join();
} return ;
}
在这里我们使用了一个 lambda 表达式替换函数指针,而结果是一样的。