线程与进程的区别使用
Threads share the address space of the process that created it; processes have their own address space.
1.线程共享创建它的进程的地址空间,进程,子进程有独立的地址空间 Threads have direct access to the data segment of its process;
2.线程共享它的进程的数据
processes have their own copy of the data segment of the parent process.
3.子进程需要拷贝自己父进程的数据,等于也是独立的数据 Threads can directly communicate with other threads of its process;
4.同一个进程的线程可以直接交互
processes must use interprocess communication to communicate with sibling processes.
进程彼此之间互相隔离,要实现进程间通信(IPC),multiprocessing模块支持两种形式:队列和管道,这两种方式都是使用消息传递的 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.
子进程的改变不影响父进程
在Cpython解释器中,同一个进程下开启的多线程,同一时刻只能有一个线程执行,无法利用多核优势
多线程用于IO密集型,如socket,爬虫,web
多进程用于计算密集型,如金融分析
from threading import Thread from multiprocessing import Process import os def work(): global n n=2 #子进程的全局n=2 # if __name__=='__main__': # n=100 # p=Process(target=work) # p.start() # p.join() # print("zhu",n) if __name__=='__main__': n=100 t=Thread(target=work) t.start() t.join() print('zhu',n) #只有一个进程,线程共享进程的数据