Greg Ravikovich Greg Ravikovich - 1 month ago 5
C++ Question

Why does this thread not know who it is?

The following code (under Visual Studio 2013) fails in the assert. Can someone explain why this happens?

#include <thread>
#include <cassert>

std::thread t;

void threadTask()
{
assert(t.get_id() == std::this_thread::get_id());
}

int main()
{
for (int i = 0; i < 1000; ++i)
{
t = std::thread(threadTask);
t.join();
}
}


I'm looking for a way to check that a function is called from a specified thread.

Answer

The thread can start running before the std::thread constructor exits back to the caller, so the assert() is likely being called before the t variable is assigned a new value. On the first loop iteration, that means t could be undefined. On subsequent iterations, it means t could still be referring to the previous thread.

The thread needs to wait until t is assigned a value before it can use t reliably. For example, by protecting t with a std::mutex:

#include <thread>
#include <mutex>
#include <cassert>

std::thread t;
std::mutex m;

void threadTask()
{
   {
   std::lock_guard<std::mutex> l(m);
   assert(t.get_id() == std::this_thread::get_id());
   }
   ...
}

int main()
{
    for (int i = 0; i < 1000; ++i)
    {
        {
        std::lock_guard<std::mutex> l(m);
        t = std::thread(threadTask);
        }
        t.join();
    }
}