Congratulations to our 2022 Qt Champions!

Which different between private QMutex in QThread and global one?

  • I study some examples and can't understand when I should use private QMutex or global?

    Global QMutex need to use for sharing varaiable access between thread and mainthread?

  • If you try to use a global instance of QMutex, all the instances of your thread will use the same mutex. Is that what you want?

    But I would say that most thread cases can be solved by using a private mutex, since you usually have only two threads (qthread and the main thread) competing for the same resource controlled by the mutex.

  • In my task I have more threads that generate some internal structures. I wish to show these datas on QTableWidget (or QTreeWidget) in MainWindow. One thread has one structure and new QTableWidgetItem to want place it on QTableWidget, another thread at the same time wants to place own QTableWidgetItem on QTableWidget. how can I use their cooperative wishes with private QMutex or not?

  • Hum...

    Let me see if I got your idea: In fact, your sharing resource is your QTableWidget and the threads are competing to use it? Well, so you have another problem than how to use mutexs.
    You shouldn't create a widget element in a thread. It's bad, and it crashs your app.

    I would suggest you to generate this data in your thread, as you're already doing. After that, emit a signal with this data, and connect it to a main thread's slot. On the main thread you can create a qtablewidgetitem and place it in your tree. Then you don't need the mutex since the signal mechanism is thread safe.

  • Of course, apart from the fact that your problem should be solved differently, you should also consider the fact that global variables are arguably evil. It's probably better to share the mutex in a smart way instead of creating a global one that is accessed by, well, everyone.

    [quote author="danilocesar" date="1288759296"]
    You shouldn't create a widget element in a thread. It's bad, and it crashs your app.[/quote]
    Technically speaking all widgets are created in a thread. As long as all widgets are created and used in the same thread as the QApplication, there is no problem at all.

  • now I'm in experiment with QGraphicsItems accessing them from threads to repaint. I emit a signal to mainthread's slot and call update(boundingRect()). that's works fine.
    next step I will try with QTablewidgetsitems.

Log in to reply