How to 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? suppose the 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 wrong, what is your idea? How can i do this?

EDIT: I solved my problem with boost :: weak_ptr. check my own answer on this page

+5
source share
4 answers

I solved my problem with 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();
     ...
}
+1
source

/, , , ( ), this . , , . , :

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

+3

reinterpret_cast , shared_ptr. . , shared_ptr, , shared_ptrs , , , .

+1

, .

If you want to pass boost::shared_ptr, you can put it in a structure that has an intrusive reference count and passes it.

It is assumed that you do not just want to pass the raw pointer and receive the receiving stream in order to delete it upon completion.

0
source

All Articles