Search code examples
c++c++11mutexstdthread

What may cause a thread id to be -1?


I've currently been playing around with concurrent objects, based on Herb Sutter's presentation. I'm currently using Visual Studio 2012 with November CTP (could not check the stuff below in another way, Clang doesn't like class members in decltypes, g++ did not like anything on Windows).

Doing so, I've faced a curious bug with a thread-id being -1. Consider the following code:

__workerThread([=]() -> void {    
    std::cerr << std::endl; 
    while (!__done) 
    { 
        this->__innerqueue.pop()(); 
    }    
})

It's just the initialization of a std::thread with a lambda function - nothing spectacular, I thought. But without the first line that forces a call to std::cerr (no optimization), this thread's id appears to be -1 (due to the debugger), while otherwise, it's like it should be.

The problem with this thread ID occurs when executing

std::unique_lock<std::mutex> lock(this->__accessMutex);

inside the message-queue, since it crashes somewhere in the lower APIs (mutex.c).

Has anyone got an idea what may cause this curious behavior ? Adding the call to std::cerr is just a nasty workaround for the moment, and I'd like to get rid of it ...

You can find the full source at Github if you want to play around with it.


Solution

  • It looks like an initializer problem. The thread runs before the concurrent queue is fully created (a race). The std::cerr probably delays the thread just long enough to make it work.

    try swapping the two lines:

    std::thread __workerThread;
    mutable concurrent::queue<std::function<void()>, std::queue> __innerqueue;
    

    Swapping should create the __innerqueue before the thread and it should work as advertised.