std::thread有一个get_id()函数可以唯一标识系统中线程。示例如下
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
std::thread::id master;
void func(int i)
{
std::string msg = std::to_string(i);
if (master == std::this_thread::get_id())
msg += ": i am number one,yeah!\n";
else
msg += ": we have the same hobby!\n";
std::cout << msg.c_str();
}
int main()
{
std::vector<std::thread> thrds;
for (int i = 0; i < 16; i++)
{
std::thread t(func, i);
thrds.push_back(std::move(t));
}
master = thrds[0].get_id();
for (int i = 0; i < 16; i++)
thrds[i].detach();
std::this_thread::sleep_for(std::chrono::seconds(4));
int a;
std::cout << "input an integer:\n";
std::cin >> a;
std::cout << "you input " << a << std::endl;
return 0;
}
在我的机器上运行结果如下: