Fundamental threading question

  • Hi guys,

    Yesterday, I asked a question about threading where I was trying to connect a signal slot from thread to main thread. The problem is actually that I am trying to signal, for example,

    @connect(thread, SIGNAL(sgGetCurrentElement(QWebElement&)), this, SIGNAL(sgGetCurrentElement(QWebElement&)));@

    As you see, I signal QWebElement&. The reason behind is that, I was using signal-slot to retrieve information from main thread. So, I was passing the address of the element which is actually set in the main there where I have QWebView.

    Now, I am asking how I should tackle this ideally. Should I again connect using signal slot to let main thread know that the thread wants to know the current element in the QWebView. Then again another signal slot but this time from main thread to thread to set the QWebElement declaring in the thread. Is this the bast way to handle this?
    What else could I do?

  • Moderators

    Right, so we have this problem again ;)

    Personally, I would avoid keeping any references to GUI objects (like QWebElement) in the thread. Separating GUI from logic is a time-consuming and usually quite boring job, but it pays later in improved maintainability and code clarity.

    There are other ways that doing two-way signal and slot connections (using mutexes, for example). You need to judge by yourself. The great, glorious advantage of queued signals and slots (Qt::QueuedConnection) is that you do not need to worry about race conditions, deadlocks in your code (and that can be a real pain to debug!).

    If you want the - probably - easiest solution, you can use a Singleton class that will be visible in both the thread and your main window, and use that to modify the lements and request new data. you can quite easily make it error-prone(ish) using QMutexLocker or QAtomic* classes. However, I think (again - my personal opinion) that in the long run, singletons are harmful because they make various classes deeply entangled and stateful.

  • Hi, usually there is no need to use references in signal slot connection with Qt classes and it should be much easier to use a "copy" and no reference a the argument.
    I have no idea what you are doing with that QWebElement, but in general Qt uses "copy on write" for most classes, so it won't copy the whole QWebElement if you pass it by value, it will just copy the internal data pointer and nothing more so it is very performant to use copy Qt objects, it will only do a deep copy if you try and modify something.
    Just in case you didn't know that, it might solve some problems you have. :)

Log in to reply