Search code examples
c++multithreadingboostboost-thread

Boost::thread how to get a pointer to the thread where my function is called?


With boost::thread how do I get a pointer to the boost::thread which is currently executing my function, from within that function?

The following does not compile for me:

boost::thread *currentThread = boost::this_thread;

Solution

  • You have to be careful because boost::thread is a movable type. Consider the following:

    boost::thread
    make_thread()
    {
        boost::thread thread([](boost::thread* p)
        {
            // here p points to the thread object we started from
        }, &thread);
        return thread;
    }
    
    // ...
    boost::thread t = make_thread();
    // if the thread is running by this point, p points to an non-existent object
    

    A boost::thread object is conceptually associated to a thread but is not canonically associated to it, i.e. during the course of the thread more than one thread objects could have been associated with it (just not more than one at a given time). That's partly why boost::thread::id is here. So what is it you want to achieve exactly?