Boost library and CreateThread win API

回眸只為那壹抹淺笑 提交于 2020-01-03 06:03:06

问题


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::thread 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()
        {

           //....
        }
  };

回答1:


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).



来源:https://stackoverflow.com/questions/6841044/boost-library-and-createthread-win-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!