网络编程之多线程——线程理论

网络编程之多线程——线程理论

1、什么是线程

在传统操做系统中,每一个进程有一个地址空间,并且默认就有一个控制线程编程

线程顾名思义,就是一条流水线工做的过程(流水线的工做须要电源,电源就至关于cpu),而一条流水线必须属于一个车间,一个车间的工做过程是一个进程,车间负责把资源整合到一块儿,是一个资源单位,而一个车间内至少有一条流水线。网络

因此,进程只是用来把资源集中到一块儿(进程只是一个资源单位,或者说资源集合),而线程才是cpu上的执行单位。多线程

多线程(即多个控制线程)的概念是,在一个进程中存在多个线程,多个线程共享该进程的地址空间,至关于一个车间内有多条流水线,都共用一个车间的资源。例如,北京地铁与上海地铁是不一样的进程,而北京地铁里的13号线是一个线程,北京地铁全部的线路共享北京地铁全部的资源,好比全部的乘客能够被全部线路拉。并发

2、线程与进程的区别

一、Threads share the address space of the process that created it; processes have their own address space.
二、Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
三、Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
四、New threads are easily created; new processes require duplication of the parent process.
五、Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
六、Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.

总结上述区别,无非两个关键点,这也是咱们在特定的场景下须要使用多线程的缘由:ide

  1. 同一个进程内的多个线程共享该进程内的地址资源
  2. 建立线程的开销要远小于建立进程的开销(建立一个进程,就是建立一个车间,涉及到申请空间,并且在该空间内建至少一条流水线,但建立线程,就只是在一个车间内造一条流水线,无需申请空间,因此建立开销小)

3、多线程应用举例

开启一个字处理软件进程,该进程确定须要办不止一件事情,好比监听键盘输入,处理文字,定时自动将文字保存到硬盘,这三个任务操做的都是同一块数据,于是不能用多进程。只能在一个进程里并发地开启三个线程,若是是单线程,那就只能是,键盘输入时,不能处理文字和自动保存,自动保存时又不能输入和处理文字。ui

相关文章
相关标签/搜索