2017-10-10 184 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:謝謝,我改進了答案。 –