Skip to content

Little trick for safe deletion of objects in a multithreaded app

Thursday, 26 July 2007  |  zander

You may have thought about using the excellent Threadweaver from kdelibs to speed up your application a bit, but got scared of the horror stories of multithreading in C++.

One common case where things may go wrong in C++ is deleting of objects. For example when you have an object like a "User". Your painting routines quite likely access that user object, for example to show that QImage of the users face. This means that you can't just delete the user object from another thread, it might still be accessed by the painting routines afterwards. Qt calls the paint event in unpredictable ways, for example when the application is uncovered by another window.

You can probably invent a way to make the user not the active user anymore and then force the other thread to wait until we are sure that main thread is not painting anymore, but that would be slow and have lots of corner cases.

Here is a much simpler way to do deletion of your objects from any thread so your main-thread won't crash due to it being removed from under it.

class SafeDeleter : public QObject {
    Q_OBJECT
public:
    SafeDeleter(User *user) : m_user(user) {
        moveToThread(QCoreApplication::instance()->thread());
        deleteLater();
    }
    ~SafeDeleter() {
        delete m_user;
    }

private:
    User *m_user;
};

And then; new SafeDeleter(myUser); myUser = 0;

What this does is delete the shape for you in the main thread, after any current paint events or input events have been completed.

Nice trick, eh?