mardi 10 octobre 2017

C++ std::this_thread::get_id() passing to cout

When using std::this_thread::get_id() on CodeBlocks using the c++11 compiler, the thread numbers start from 2. Every time I run the code bellow it prints threads 2 - 6 instead of 0 - 4. Why?

Could it be possible that some other c++ application that is running in the background is using up thread IDs 1 and 2? What sorcery is this?

#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;
}

Aucun commentaire:

Enregistrer un commentaire