Boost logo

Boost Users :

Subject: Re: [Boost-users] [thread] getting thread id number
From: Rush Manbert (rush_at_[hidden])
Date: 2009-04-24 17:24:13


On Apr 24, 2009, at 11:47 AM, Hipatia wrote:

>
> Hi!
>
> I'm trying to get the id number of a thread just to write it to the
> standard
> output.
>
> Since I'm not an expert in c++ programming, let me explain what I do
> (even
> if it's quite simple): a create an instance as follows,
> boost::thread::id thread_id= boost::this_thread::get_id();
> By debugging my code with Visual Studio, I see that 'thread_id' has an
> 'unsigned int' object member called 'id', so I would like to display
> this
> value.
> Unfortunately, I cannot find in the boost documentation any function
> member
> of boost::thread::id class that returns its value.

The id class defined operator<<, so just do this:

std::cout << "Thread id is: " << boost::this_thread::get_id();

I just did a replacement of a pthread implementation with a boost
thread implementation, and I needed to get the numeric value of the
data member, which I did like this (Thread::id_t is a typedef for
uint64_t):

   Thread::id_t getId() {
     std::stringstream ios;
     // This needs to be a pointer because on a *nix system,
this_thread::get_id()
     // returns an object that defines operator<< to write the
pthread_t to the stream,
     // and it's a pointer, so it gets formatted as hex and we can't
change that by
     // inserting a dec manipulator. So when we read out of the
stream, we need to
     // read into something for which a hex format makes sense.
Stupid. Just stupid.
     void *numericId;

     ios << this_thread::get_id();
     ios >> numericId;
     // And, of course, static_cast can't be used to convert from
void* to the integer type.
     return (Thread::id_t)numericId;
  }

It's a hack, I know, but I couldn't think of anything else.

- Rush


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net