开发者

Boost library and CreateThread win API

I have a class such as :

class MyStreamReader
{
public:
    MyStreamReader(MyPramameter myPram) {.....}
    ~MyStreamReader() {}

    DWORD WINAPI  ReaderThread(LPVOID *lpdwThreadParam ) 

    {

       //....
    }
};

and i want to call ReaderThread with WinAPI CreateThread. But CreateThread wants ReaderThread function wants a static function.

In some forms it is said that this is possible with boost library such as :

CreateThread(NULL, 0, boost::bind(&MyStreamReader::ReaderThread,this),

(void*)&myParameterObject), 0, NULL);

But i got compilation error:

'CreateThread' : cannot convert parameter x from 'boost::_bi::bind_t<R,F,L>' 

to 'LPTHREAD_START_ROUTINE'

So as a result my questions:

  1. Is it possible to call non-static function of a class from CreateThread using boost lib(or any other method)
  2. If not any C++ THREADing librray you may recomend(for visual C++) which i can call-run non static member function of a class as a thread?

Best Wishes

Update:

So first question: It seesm that it is impossible to call non-static c++ member function from CreateThread win API...

So any recomandations for C++ Multithreading lib whic is possible to call non-static functions as threads...

Update 2: Well i try boost thread lib...seems it works...

MyStreamReader* streamReader = new MyStreamReader(myParameters);


boost::thread GetStreamsThread

   ( boost::bind( &MyStreamReader::ReaderThread, streamReader ) );

or (no need for bind)

boost::threa开发者_C百科d GetStreamsThread(&MyStreamReader::ReaderThread, streamReader);

AND in order to use boost::thread i update my class definition as:

class MyStreamReader
  {
    public:
        MyStreamReader(MyPramameter myPram) {.....}
        ~MyStreamReader() {}

        void ReaderThread()
        {

           //....
        }
  };


One common answer to this is to use a static "thunk":

class Worker
{
    public :
        static DWORD Thunk(void *pv)
        {
            Worker *pThis = static_cast<Worker*>(pv);
            return pThis->DoWork();
        }

        DWORD DoWork() { ... }
};

...

int main()
{
    Worker worker;
    CreateThread(NULL, 0, &Worker::Thunk, &worker);
}

You can, of course, pack more parameters into your call to pv. Just have your thunk sort them out correctly.

To answer your question more directly, boost::bind doesn't work with the Winapi that way. I would advise using boost::thread instead, which does work with boost::bind (or, if you have a C++0x compiler, use std::thread with std::bind).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜