线程的概念
进程只是用来把资源集中到一起(进程只是一个资源单位,或者说资源集合),而线程才是cpu上的执行单位。
三 线程与进程的区别
1
1.线程的创建开销小(无需申请内存空间或者资源),创建线程的速度快,(但是不能无限开)
2.同一个进程下的多个线程,共享该进程地址空间的资源(数据等内容)
3.改变线程,会影响其他线程(在同一个进程的内存空间内的线程) 但是改变主进程,不会影响子进程
- 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.
四 为何要用多线程
多线程指的是,在一个进程中开启多个线程,简单的讲:如果多个任务共用一块地址空间,那么必须在一个进程内开启多个线程。详细的讲分为4点:
1. 多线程共享一个进程的地址空间
2. 线程比进程更轻量级,线程比进程更容易创建可撤销,在许多操作系统中,创建一个线程比创建一个进程要快10-100倍,在有大量线程需要动态和快速修改时,这一特性很有用
3. 若多个线程都是cpu密集型的,那么并不能获得性能上的增强,但是如果存在大量的计算和大量的I/O处理,拥有多个线程允许这些活动彼此重叠运行,从而会加快程序执行的速度。
4. 在多cpu系统中,为了最大限度的利用多核,可以开启多个线程,比开进程开销要小的多。(这一条并不适用于python)
开启线程的两种方式
与开启进程的方式类似
from threading import Thread def piao(name,n): print('%s is piaoing %s and%s'%(name,n,os.getpid())) if __name__ == '__main__': t=Thread(target=piao,args=('alex',11,)) #这里的写法要注意, t.start() print('zhu')