Skip to content

Question about executing context #35

@durkmurder

Description

@durkmurder

I use qtpromise a lot in my project and I am constantly running into next situation

static QtPromise::QPromise<void> DoSomething()
{
    return QtPromise::resolve().delay(5000);
}
////
struct Foo : public QObject {
    void doSomethingAndDoSomethingElse()
    {
        QPointer<Foo> self(this);
        DoSomething().then([self] {
            if(self) {
                // do something with self.
                qDebug() << "Self is ok";
            }
            else {
                qDebug() << "Foo already deleted";
            }
        });
    }
};

Foo *foo = new Foo;
foo->doSomethingAndDoSomethingElse();
// here foo gets deleted(by deleteLater for instance)

So it can happen that Foo gets deleted before promise is resolved, and since function is called as callback I need to check if this is still valid in some way otherwise I get segfault.
I was thinking a lot about it and it seems like a pretty common thing.
I see 3 ways how to resolve this situation.

  1. Check this as I am doing it right now.
  2. Store started promises and wait for them in destructor.
  3. Try to support same behavior as Qt signal & slots system in terms of executing slot in receivers context.
    I like 3rd case the most but it requires changes to the library(which I can do). I want to discuss here if it makes sense at all and if you see any problems with it.
    So the idea is to provide executing context to continuations, introduce new call like, thenVia(QObject *, callback) or something like then(callback).via(QObject*) which will be used as context for delivering callback. If such functionality exists then my use case will be resolved just by using context for continuations since if context is already deleted, callback won't be executed(same behavior with slots). Implementation wise it shouldn't be that hard to do it, since it requires just some modifications to qtpromise_defer.

Looking forward to discussing it

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions