多进程与多线程
进程(Process)
是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础
线程(Thread)
有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。线程是进程中的一个实体,是被系统独立调度和分派的基本单位,一个进程可以包含多个线程,但是线程不能包含多个进程。线程自己不拥有系统资源,在单个程序中同时运行多个程序完成不同的工作,称为多线程
多线程的优点:
a、使用线程可以把占据长时间的程序中的任务放到后台去处理
b、用户界面可以更加吸引人,这样,比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度
c、程序的运行速度可能加快
d、在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了
线程与进程的区别
线程和进程的区别在于:子进程和父进程有不同的代码和数据空间,而多个线程则共享数据空间,每个线程有自己的执行堆栈和程序计数器为其执行上下文,该上下文反映了线程上次运行该线程的CPU寄存器的状态
每个独立的进程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制
a、线程可以被抢占(中断)
b、在其他线程正在运行时,线程可以暂时搁置(也称为睡眠)—这就是线程的退让
python中使用线程的两种方式:函数或者用类来包装线程对象
一、单线程实践应用
单线程在程序执行时,所走的程序路径按照顺序排下来,前面的必须处理好,后面的才会执行
案例:一个学生先用2秒说话,接着用3秒写字,最后结束
from time import ctime,sleep #ctime获取当前时间,sleep是延时
#定义线程函数
def talk():
print("Start talk %r" %ctime())
sleep(2)
def write():
print("Start Write! %r" %ctime())
sleep(3)
if __name__=="__main__":
talk()
write()
print("All end %r" %ctime())
if__name__==“__main__”:表示如果当前模块是被直接运行的,则该语句之后代码块被运行,如果模块是被导入的,则代码块不被运行
二、多线程实践应用
多线程(MultiThreading)是指从软件或者硬件上实现多个线程并发执行的技术
案例:让学生同时进行说和写的操作
from time import ctime,sleep
import threading #导入线程模块
#为线程定义函数,定义说和写的方法
def talk(content,loop): #content定义说的内容,loop定义循环的次数
for i in range(loop):
print("start talk %s %s" %(content,ctime()))
sleep(3)
def write(content,loop):
for i in range(loop):
print("start write %s %s" %(comtent,ctime()))
sleep(5)
threads=[] #定义一个threads,空列表
#定义加载两个线程,t1是读的线程,t2是写的线程
t1=threading.Thread(target=talk,args=('Speak:Hello,haha',2))
threads.append(t1)
t2=threading.Thread(target=write,args=('Write:life is short',2))
threads.append(t2)
#执行多线程
if __name__=='__main__':
for t in threads:
t.start()
for t in threads:
t.join()
print("All the End %r " %ctime())
线程模块
python通过两个标准库thread和threading提供对线程的支持。thread提供了低级别的、原始的线程以及一个简单的锁
threading模块提供的其它方法:
threading.currentThread():返回当前的线程变量
threading.enumerate():返回一个包正在运行的线程的list。正在运行指线程启动后,结束前,不包括启动前和终止后的线程
threading.activeCount():返回正在运行的线程数量,与len(threading.enumerate())有相同的结果
除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了一下方法:
run():用以表示线程活动的方法
start():启动线程活动
join([time]):等待至线程中止。这阻塞调用线程直至线程的join()方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生
isAlive():返回线程是否活动的
getName():返回线程名
setName():设置线程名
三、多进程实践应用
与多线程相比,多进程就是 import multiprocessing,然后替换相应的方法multiprocessing.Process()
使用多进程的例子
from time import ctime,sleep
import multiprocessing
#定义两个方法的说和写
def talk(content,loop):
for i in range(loop):
print("talk:%s %s" %(content,ctime()))
sleep(2)
def write(content,loop):
for i in range(loop):
print("write:%s %s" %(content,ctime()))
sleep(3)
#定义两个进程
process=[]
p1=multiprocessing.Process(target=talk,args=('Python',2))
process.append(p1)
p2=multiprocessing.Process(target=write,args=('hello',2))
process.append(p2)
#调用进程
if__name__='__main__'
for p in process:
p.start()
for p in process:
p.join()
print("all process in run! %s" %ctime())
四、相关延伸
进程间通信IPC(Interprocess communication)
线程锁、进程锁
生命周期
进程调度