当使用std::this_thread::get_id()编译器在CodeBlocks上使用c++11时,线程号从2开始。每次我运行下面的代码时,它都会打印线程2-6而不是0- 4。为什么?
是否有可能在后台运行的其他c++应用程序正在使用线程ID 1和2?这是什么巫术?
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
std::mutex m;
class TClass
{
public:
void run()
{
m.lock();
cout << "Hello, I'm thread " << std::this_thread::get_id() << endl;
m.unlock();
}
};
int main()
{
TClass tc;
std::thread t[5];
for (int i=0; i<5; i++)
{
t[i] = std::thread(&TClass::run, &tc);
}
for (int i=0; i<5; i++)
{
t[i].join();
}
cout << "All threads terminated." << endl;
}发布于 2017-10-10 08:38:08
不能保证std::this_thread::get_id()返回的值。您不能假设该值将从零开始或将是顺序的。这是未指定的。
https://stackoverflow.com/questions/46662117
复制相似问题