[Solved] Good way to wait until processing a event is done?



  • I'm writing a multi-threaded code.
    In my code, a thread should wait until QCoreApplication::postEvent is done.
    I think QMutex is not a good way to do it because A QMutex must be unlocked in the same thread that locked it.
    And I cannot use QCoreApplication::sendEvent because there is some UI thread depended jobs on the event handler's side.

    @MyEvent event = new MyEvent();
    QCoreApplication::postEvent(object, event);
    // wait the event is processed...
    // do next thing here..
    @

    Maybe I can send a reference of local variable (such as bool type) via event object and wait the variable is changed, like below, but I wand to use some more elegant way.

    @bool processed = false;
    MyEvent event = new MyEvent(processed);
    QCoreApplication::postEvent(object, event);
    // wait the event is processed...
    while(!processed)
    {
    sleep(1);
    }
    // do next thing here..
    @

    @class MyEvent:public QEvent
    {
    public:
    MyEvent(bool& flag):QEvent((QEvent::Type)MY_EVENT), processed(flag)
    {
    }
    virtual ~MyEvent() {processed = true;};
    private:
    bool& processed;
    };
    @



  • If you must wait until the event has been processed and sendEvent cannot be used, you should reconsider whether you actually have to wait for the event to be processed.

    What is the purpose of this exercise? What do you want to achieve (not the waiting part, the bigger picture)?



  • [quote author="Franzk" date="1305088214"]If you must wait until the event has been processed and sendEvent cannot be used, you should reconsider whether you actually have to wait for the event to be processed.

    What is the purpose of this exercise? What do you want to achieve (not the waiting part, the bigger picture)?[/quote]

    The thread procedure is created by an open-source library for a specific network protocol (XMPP) and the event is the first notification from the thread which requests to create a new UI to display the following events from the thread before the method is returned (as soon as the method is returned, the thread begins to notify additional events for the new UI).



  • Right. Well, I've seen "wait conditions":http://doc.trolltech.com/latest/qwaitcondition.html being used in a similar manner to your processed flag. The advantage of using wait conditions is that you won't have a busy wait loop. It'll be a bit nicer/cleaner than a simple boolean and as you noticed in your problem statement, QMutex probably won't work given the thread thingy.

    If there's only one GUI item that displays these messages, you could consider creating it beforehand and showing it on receiving this event. Then you don't have to wait for completion.



  • Thank you Franzk.
    QWaitCondition is really suitable for me.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.