|
Boost Users : |
From: Andrew Holden (aholden_at_[hidden])
Date: 2007-12-19 12:33:50
Andrew Holden [aholden_at_[hidden]] wrote:
> STenyaK (Bruno Gonzalez) [stenyak_at_[hidden]] wrote:
>> Ok. This is how my code structure looks:
>> ----------------------------
>> typedef shared_ptr<MyClass> pMyClass;
>> void* MyClass::actionThread(void *objectPointer) {
>> pMyClass * _obj = static_cast<pMyClass*>(objectPointer);
>> pMyClass obj = *_obj; obj->action(false);
>> delete _obj;
>> }
>> void MyClass::action(bool threaded)
>> {
>> if (threaded)
>> {
>> pthread_t tid;
>> pthread_create(&tid, 0, actionThread, new pMyClass(this))
>> } else {
> //TODO: actually perform the action
>> }
>> }
>> ----------------------------
>
> ----------------------------
> typedef shared_ptr<MyClass> pMyClass;
> void* MyClass::actionThread(void *objectPointer) {
> MyClass * _obj = static_cast<MyClass*>(objectPointer);
> pMyClass obj = _obj->shared_from_this();
> obj->action(false);
> }
>
> void MyClass::action(bool threaded)
> {
> if (threaded)
> {
> pthread_t tid;
> pthread_create(&tid, 0, actionThread, this) } else {
> //TODO: actually perform the action
> }
> }
> ----------------------------
I just realized you should ignore this implementation because it
contains a race condition (main thread may delete the object before
actionThread can call shared_from_this. Here is a tweak for your
version that uses shared_from_this:
----------------------------
typedef shared_ptr<MyClass> pMyClass;
void* MyClass::actionThread(void *objectPointer) {
pMyClass * _obj = static_cast<pMyClass*>(objectPointer);
pMyClass obj = *_obj;
delete _obj;
obj->action(false);
}
void MyClass::action(bool threaded)
{
if (threaded)
{
pthread_t tid;
//Change next line:
pthread_create(&tid, 0, actionThread, new
pMyClass(shared_from_this()))
} else {
//TODO: actually perform the action
}
}
----------------------------
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net