Andrew Holden [aholden@charteroaksystems.com] wrote:
STenyaK (Bruno Gonzalez) [stenyak@gmail.com] wrote:
Ok. This is how my code structure looks: ---------------------------- typedef shared_ptr<MyClass> pMyClass; void* MyClass::actionThread(void *objectPointer) { pMyClass * _obj = static_cast
(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
(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