PDA

View Full Version : What is the "main thread"? Why is it special?



tksharpless
4th December 2010, 16:42
Many places in the Qt docs we are warned that the QApplication must only be created on the "main thread", and similarly for all GUI objects. But there is no explanation. Does "main thread" really mean the one created by the OS to start a new process? And if so, why does QApplication require that? Couldn't it just as well live on any thread of a process?

I'm asking because (like many others) I would like to add a Qt-based GUI to an existing command line program, something like this: the app creates a new thread to run the gui initialization routine, which creates a QApplication and calls its exec(). Then the app 'main' thread creates a QObject that sets up queued signal connections to gui functions, and emits those signals in fns callable from the app. Any required blocking/unblocking of the main thread is handled outside Qt (e.g. in libpthread). It seems to me this satisfies the thread-safeness rules of Qt, except possibly "the QApplication must live on the main thread". Why shouldn't it work?

Thanks for your advice
-- Tom

squidge
4th December 2010, 23:22
You can put it in a seperate thread if you wish, as long as only a single thread interfaces with the UI.

However, this might not be portable (which is the idea of Qt). For example, I've heard that such applications do not work properly on Mac OS (Note however that I do not have first hand experience of this, it's only what I've read)

tksharpless
5th December 2010, 00:04
Thanks squidge,

In fact the scheme I described is working, on Windows with the MinGW build tools (Qt 4.6 opensource). But still at an early stage of development, and it is pretty easy to write things that crash.

The project is an interactive video transcoder derived from ffmpeg. I'm hoping the present scheme (ffmpeg on main thread) will be viable on Win32 and Linux (I've had problems with Qt on OSX before, so I'm not counting on that platform). But if it turns out that QApplication really does need to own the main thread, I can arrange to run ffmpeg on a worker thread.

-- Tom