[Solved]Mixing QtThread and std::thread, possible ?
-
Hi!
I 've a class that refresh the widget with a QTimer, I've another class that use a thread to update the scene.
I want to use an std::condition_variable to avoid that qt display an empty image list when the other thread has not finish to update the scene.
I use an algorithm who put in a vector what part of the world is visible by the user.But when I trid this in the update method (the method who displays everything.) I got an exception.
Here's the code :
@try {
unique_lock<mutex> locker(g_lock_update_scene);
g_signal.wait(locker, & { return !parent->getSceneUpdater()->isGDone();});
} catch (exception &e) {
cerr<<e.what()<<endl;
}@And the message is : std::system_error operation not permitted.
I tested with another source code without Qt and it works fine. :/
Should I use an std::thread instead of a QTimer to display the elements ?
-
Hi,
Since you are using Qt, why not use "QWaitCondition":http://qt-project.org/doc/qt-4.8/qwaitcondition.html ? So no need to mix different things
-
Finally it seems that QTimer don't use a QThread, the problem wasn't what I thought, and for portability, it's recommended to do the displayings and evenements management in the main thread.
I solved the problem by declaring the condition variable in a global scope rather than in the QMainFrame and it works.
I don't know why but... -
No it doesn't, QTimer uses timers from the underlying system.
Everything graphical must be done in the main thread (AKA GUI thread).
Event managements are handled by the event loop, either the main, or the one from the QThread your objects have affinity with but that's another topic.
Are you sure that having the wait condition in a global scope is the right approach ?
-
No, I don't know what's exactly the right approach to do that, I'm a novice in this domain and I do it just for fun. (the multi-threading.)
Then I take what it works. xD
I've just a file nammed globals.h that contains all the globals variables. (They are all static.)Before I declared the condition_var in the QMainFrame ans I passed it at my rendercomponent and at my sceneupdater but that didn't work.
But for the unique_lock for the mutex, I need to declare the mutex in the QMainFrame and to pass it to the rendercomponent and to the sceneupdater otherwhise the notify_one don't work ans the main thread is nerver awaken.
-
Then please, start by reading some books about it (there are good references given in Qt's documentation) as well as the threading classes documentation.
Threading is one of those thing that can unleash hell if not done properly.
The "fix on failure" and "move thing around until it works" approaches are to ban when using threads.