简体   繁体   中英

How to retrieve the thread id from a boost::thread?

I want to be able to identify threads by a simple id when logging so that it is easy to trace the execution of a single thread. With windows using the API GetCurrentThreadId() can achieve what I want. In boost::thread there is a method get_id() but this doesn't represent an integral value like an integer. This object does have a thread_data member which contains an id which seems to be what I want but the data member is private so can't be accessed.

What is the boost way to access the thread id for display or identification purposes?

Too late, but for users looking for an answer, boost allows to consult the thread id as you said, simply calling the following method:

boost::this_thread::get_id()

This method returns a internal id type from boost, that is not numeric as you want. But you can easily convert this number to, for example, an unsigned long taking into account that the id has as hexadecimal representation. This little function will do de Job:

#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>

unsigned long getThreadId(){
    std::string threadId = boost::lexical_cast<std::string>(boost::this_thread::get_id());
    unsigned long threadNumber = 0;
    sscanf(threadId.c_str(), "%lx", &threadNumber);
    return threadNumber;
}

void drawThreadId(){
    std::cout << getThreadId() << std::endl;
    boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}

int main() {
    for(int i=0; i<10; i++){
        boost::thread thread = boost::thread(drawThreadId);
    }
    return 0;
}

This will return something like this:

4491075584
4491612160
4492148736
4492685312
4493221888
4493758464
4494295040
4494831616
4495368192
4495904768

Do not forget link with boost_thread and boost_system.

Hope this helps!

Boost includes an operator<<(std::ostream&, const boost::thread::id&) overload that can be used to write a thread id to a stream (actually, the overload is a template and will work with any specialization of std::basic_ostream , not just std::ostream ).

The result of printing the id is likely platform-specific, since different platforms may use different internal representations for thread identifiers.

You need to use the member function boost::thread::native_handle() . It returns a type native_handle_type which is an implementation defined alias for a native thread identifier, which can then be used with native thread API functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM