程序、进程(Process)、线程(Thread)
程序:由源代码生成的可执行应用。 (例如:QQ.app)
进程:一个正在运行的程序可以看做一个进程,(例如:正在运行的QQ就是一个进程),进程拥有独立运行所需要的全部资源
线程:程序中独立运行的代码段。(例如:接收QQ消息的代码)
一个进程是由一或多个线程组成,进程只负责资源的调度和分配,线程才是程序真正的执行单元,负责代码的执行。单线程
每个正在运行的程序(即进程),至少包括一个线程,这个线程叫主线程
主线程在程序启动时被创建,用于执行main函数
只有一个主线程的程序,称作单线程程序
主线程负责执行程序的所有代码(UI展现以及刷新,网络请求,本地存储等等)。这些代码只能顺序执行,无法并发执行
多线程
拥有多个线程的程序,称作多线程程序。
iOS允许用户自己开辟新的线程,相对于主线程来讲,这些线程,称为子线程
可以根据需要开辟若干子线程
子线程和主线程都是独立的运行单元,各自的执行互不影响,因此能够并发执行单线程、多线程的区别
单线程程序:只有一个线程,代码顺序执行,容易出现代码阻塞(页面假死)
多线程程序:有多个线程,线程间独立运行,能有效地避免代码阻塞,并且提高程序的运行性能
其他
The process model is based on two independent concepts: resource grouping and execution. Sometimes it is useful to separate them; this is where threads come in….
One way of looking at a process is that it is
a way to group related resources together. A process has an address space containing program text and data, as well as other resources. These resource may include open files, child processes, pending alarms, signal handlers, accounting information, and more. By putting them together in the form of a process, they can be managed more easily. The other concept a process has is
a thread of execution, usually shortened to just thread. The thread has a program counter that keeps track of which instruction to execute next. It has registers, which hold its current working variables. It has a stack, which contains the execution history, with one frame for each procedure called but not yet returned from. Although a thread must execute in some process, the thread and its process are different concepts and can be treated separately.
Processes are used to group resources together; threads are the entities scheduled for execution on the CPU
From section 2.2.2 The Classical Thread Model in Modern Operating Systems 3e by Tanenbaum
总的来说,线程就是建立在进程上的一次程序运行单位。而进程虽然包含程序,但它的作用不是去执行程序,而是负责资源分配。
资料来自:知乎和园子
https://www.zhihu.com/question/25532384
https://www.cnblogs.com/496668219long/p/4517911.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/151231.html