为什么单线程模型用于更新 UI 作为主线程? [英] Why is a single threaded model used to update the UI as main thread?

查看:29
本文介绍了为什么单线程模型用于更新 UI 作为主线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Qt 文档说,

如前所述,每个程序在启动时都有一个线程.这线程被称为主线程"(在Qt 应用程序).Qt GUI 必须在这个线程中运行.

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.

Android 文档说,

The Android doc says,

与活动和其他组件一样,服务运行在主应用进程的线程

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

还有 iOS,

强烈建议不要从后台线程(例如计时器、通讯等).这可能是导致有时很难识别的崩溃.而是使用这些强制代码在 UI 线程上执行(这始终是主"线程).

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).

为什么他们使用单线程模型来更新 UI?

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

推荐答案

简而言之,这是确保显示不损坏的唯一合理方法.

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

长答案是,允许多个线程更新 UI 会导致死锁、竞争条件和各种麻烦.这是 Java 的 AWT(以及其他 UI 系统)所教给我们的惨痛教训,它允许多个线程接触 UI.例如,请参阅 多线程工具包:一个失败的梦想?.该帖子(通过死链接)引用 Why Threads Are A坏主意Threadaches.

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.

这篇关于为什么单线程模型用于更新 UI 作为主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆