Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I pass 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

like image 532
Behrouz.M Avatar asked Feb 24 '11 08:02

Behrouz.M


3 Answers

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

like image 168
neuro Avatar answered Oct 26 '22 06:10

neuro


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.

like image 1
FireAphis Avatar answered Oct 26 '22 07:10

FireAphis


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();
     ...
}
like image 1
Behrouz.M Avatar answered Oct 26 '22 08:10

Behrouz.M