2017-10-10 186 views
0

在使用C++ 11编译器的CodeBlocks上使用std::this_thread::get_id()时,线程编号从2开始。每次运行代码时,它都会打印2-6线程为0 - 4。为什么?C++ std :: this_thread :: get_id()传递给cout

是否有可能在后台运行的其他一些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; 
} 
+1

您的主线在第一个线程 – user463035818

回答

4

对于std::this_thread::get_id()返回的值不能保证。您不能认为该值将从零开始或将是连续的。那就是未指定

+0

@PeteBecker:谢谢,我改进了答案。 –