开发者

How can I pass boost::shared_ptr as a pointer to a Windows Thread function?

How can I pas开发者_JS百科s boost::shared_ptr as a pointer to a Windows Thread function ? assume following code :

test::start()
{
    ....
    _beginthreadex( NULL, 0, &test::threadRun, &shared_from_this(), 0, &threadID );

    ...
    ...
}

/*this is a static function*/
UINT __stdcall test::threadRun( LPVOID lpParam )
{ 
     shared_ptr<test> k = *static_cast< shared_ptr<test>* >(lpParam);
     ...
}

I think this code is incorrect, what is your idea ? how can I do this ?

EDIT : I solved my problem by boost::weak_ptr. check my own answer in this page


When you have to pass parameter from a class to a static function/method and what you have is a callback parameter (usual in thread callbacks), I usually pass this to the callback. This way you have one simple cast and you have access to all members of your class. Practically, the callback is as a member of your class :

test::start()
{
    // [...]
    _beginthreadex(NULL, 0, &test::threadRun, this, 0, &threadID);
    // [...]
}

// this is a static function
UINT __stdcall test::threadRun(LPVOID lpParam)
{ 
     test* self = static_cast<test*>(lpParam);

     // do whatever you want with all the instance members :)

     self->getMyShared();
     self->useMyGreatMemberMethof();

     // ...
}

my2c


You should use a reinterpret_cast and take care that you hold at least one shared_ptr during the spawning. Otherwise your object will be destroyed. That is, since you pass a pointer to shared_ptr, you won't enjoy the usual pointer protection and if all your existing shared_ptrs are destroyed, then when your thread is spawned it will contain an illegal pointer.


I solved my problem by boost::weak_ptr:

test::start()
{
    ....
    shared_ptr<test> shPtr = shared_from_this();
    boost::weak_ptr<test> wPtr=shPtr;
    _beginthreadex( NULL, 0, &test::threadRun, &wPtr, 0, &threadID );

    ...
    ...
}

/*this is a static function*/
UINT __stdcall test::threadRun( LPVOID lpParam )
{ 
shared_ptr<test> k      = static_cast< boost::weak_ptr<test>* >(lpParam)->lock();
     ...
}


This is one of the situations actually where intrusive reference counting works well.

If you want to pass the boost::shared_ptr you can put it into a struct that has intrusive reference counting and pass it in.

This is assuming you don't just want to pass in a raw pointer and get the receiving thread to delete it when finished.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜