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
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();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With