Getting boost :: thread id for PostThreadMessage

I have a Visual Studio 2008 C ++ project using Boost 1.47.0, where I need to get my own Windows id for boost :: thread to go to PostThreadMessage.

On Windows Vista and 7, I would just do this:

DWORD thread_id = ::GetThreadId( mythread.native_handle() );

This is good, but I also need my application to work in XP, where it GetThreadIddoes not exist.

I found that boost: thread stores the thread id value in the boost :: thread :: id private data element thread_data. I can do this with a few unpleasant throws:

boost::detail::thread_data_base* tdb = *reinterpret_cast< boost::detail::thread_data_base** >( &message_thread.get_id() );
DWORD thread_id = tdb->id;

But I'm starting to get compiler warnings for referencing a temporary object boost::thread::id.

warning C4238: nonstandard extension used : class rvalue used as lvalue

? , , .

, PaulH

+5
1

/ , , Johannes Schaub - litb , : . . , (, , ):

#include <windows.h>
#include <iostream>

#include "boost/thread.hpp"

using namespace std;


// technique for accessing private class members
//
//  from: http://bloglitb.blogspot.com/2011/12/access-to-private-members-safer.html
//

template<typename Tag, typename Tag::type M>
struct Rob { 
  friend typename Tag::type get(Tag) {
    return M;
  }
};

struct thread_data_f {
    typedef unsigned boost::detail::thread_data_base::*type;

    friend type get(thread_data_f);
};

struct thread_id_f {
    typedef boost::detail::thread_data_ptr boost::thread::id::*type;

    friend type get(thread_id_f);
};

template struct Rob<thread_data_f, &boost::detail::thread_data_base::id>;
template struct Rob<thread_id_f, &boost::thread::id::thread_data>;

unsigned int get_native_thread_id( boost::thread const& t)
{
    boost::detail::thread_data_ptr thread_data = t.get_id().*get(thread_id_f());
    unsigned thread_id = (*thread_data).*get(thread_data_f());

    return thread_id;
}

//
//
//


// test of get_native_thread_id()


void thread_func()
{
    cout << "thread running..." << endl;

    cout << "Windows says my ID is: " << GetCurrentThreadId() << endl;

    for (;;) {
        boost::this_thread::yield();
    }
}


int main()
{
    boost::thread t(thread_func);

    ::Sleep(2000);

    cout << "boost says my thread ID is: " << get_native_thread_id(t) << endl;

    return 0;
}

, " " . , - . :

  • MinGW 4.6.1 -Wall -Wextra - . " " script.
  • V++ 2008 2010 /W 4

, , :

C:\temp>test
thread running...
Windows says my ID is: 5388
boost says my thread ID is: 5388

, , , / boost:: thread , , , .


/:

"", , ++ 03 14.7.2/8 " ":

, . [: , , ( , ) , , - -, .]

"", , , :

, : . !

+6

All Articles