Why is a single threaded model used to update the UI as main thread?
Asked Answered
R

2

13

The Qt doc says,

As mentioned, each program has one thread when it is started. This thread is called the "main thread" (also known as the "GUI thread" in Qt applications). The Qt GUI must run in this thread.

The Android doc says,

Like activities and the other components, services run in the main thread of the application process

And iOS,

It is strongly recommended not to update UI controls etc from a background thread (e.g. a timer, comms etc). This can be the cause of crashes which are sometimes very hard to identify. Instead use these to force code to be executed on the UI thread (which is always the “main” thread).

Why does they use a single threaded model to update UI ?

Reiterant answered 2/8, 2012 at 7:11 Comment(1)
It increases complexity and has no benefit. See also #5544947Dorothydorp
A
26

The short answer is, it's the only reasonable way to ensure that the display is not corrupted.

The long answer is that allowing multiple threads to update the UI results in deadlocks, race conditions, and all sorts of trouble. This was the painful lesson taught by Java's AWT (among other UI systems) that allows multiple threads to touch the UI. See, for instance, Multithreaded toolkits: A failed dream?. That post refers (via dead links) to Why Threads Are A Bad Idea and Threadaches.

Appraisal answered 2/8, 2012 at 7:14 Comment(3)
Multithreaded toolkits link leads to 404 now. Is there somewhere a valid link?Henrie
@Henrie - Hm. It seems to have disappeared from the web. It seems like it's even been removed from the Internet Archive. Bummer.Appraisal
@Henrie - I found a copy here: titanwolf.org/Network/Articles/…Appraisal
P
0

iOS and Android force you to work with UI only from main thread. The reason is the same as a shared object, thread safe[About]... in multithread environment

Android example error

FATAL EXCEPTION: Thread-19449
E/AndroidRuntime: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views

iOS example error

This application is modifying the autolayout engine from a background thread" error?
Paterson answered 30/9, 2022 at 13:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.