[TOC]
线程
python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的,可以更加方便的被使用
使用threading模块 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 import threadingimport timedef saySorry () : print("对不起" ) time.sleep(1 ) if __name__ == "__main__" : for i in range(5 ): t = threading.Thread(target=saySorry) t.start() length = len(threading.enumerate()) print('当前运行的线程数为:%d' %length)
线程代码的封装 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import threadingimport timeclass MyThread (threading.Thread) : def run (self) : for i in range(3 ): time.sleep(1 ) msg = "I'm " +self.name+' @ ' +str(i) print(msg) if __name__ == '__main__' : t = MyThread() t.start()
共享全局变量 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 from threading import Threadimport timeg_num = 100 def work1 () : global g_num for i in range(3 ): g_num += 1 print("----in work1, g_num is %d---" %g_num) def work2 () : global g_num print("----in work2, g_num is %d---" %g_num) print("---线程创建之前g_num is %d---" %g_num) t1 = Thread(target=work1) t1.start() time.sleep(1 ) t2 = Thread(target=work2) t2.start()
线程安全问题 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 import threadingimport timeg_num = 0 def work1 (num) : global g_num for i in range(num): g_num += 1 print("----in work1, g_num is %d---" %g_num) def work2 (num) : global g_num for i in range(num): g_num += 1 print("----in work2, g_num is %d---" %g_num) print("---线程创建之前g_num is %d---" %g_num) t1 = threading.Thread(target=work1, args=(1000000 ,)) t1.start() t2 = threading.Thread(target=work2, args=(1000000 ,)) t2.start() while len(threading.enumerate()) != 1 : time.sleep(1 ) print("2个线程对同一个全局变量操作之后的最终结果是:%s" % g_num)
同步互斥 1 2 3 4 5 6 mutex = threading.Lock() mutex.acquire() mutex.release()
demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 import threadingimport timeg_num = 0 def test1 (num) : global g_num for i in range(num): mutex.acquire() g_num += 1 mutex.release() print("---test1---g_num=%d" %g_num) def test2 (num) : global g_num for i in range(num): mutex.acquire() g_num += 1 mutex.release() print("---test2---g_num=%d" %g_num) mutex = threading.Lock() p1 = threading.Thread(target=test1, args=(1000000 ,)) p1.start() p2 = threading.Thread(target=test2, args=(1000000 ,)) p2.start() while len(threading.enumerate()) != 1 : time.sleep(1 ) print("2个线程对同一个全局变量操作之后的最终结果是:%s" % g_num) ''' ---test2---g_num=1839708 ---test1---g_num=2000000 2个线程对同一个全局变量操作之后的最终结果是:2000000 '''
ps: 要避免死锁问题
进程 进程的创建-multiprocessing
multiprocessing模块就是跨平台版本的多进程模块,提供了一个Process类来代表一个进程对象,这个对象可以理解为是一个独立的进程,可以执行另外的事情
demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from multiprocessing import Processimport timedef run_proc () : """子进程要执行的代码""" while True : print("----2----" ) time.sleep(1 ) if __name__=='__main__' : p = Process(target=run_proc) p.start() while True : print("----1----" ) time.sleep(1 )
进程pid 1 2 3 4 5 6 7 8 9 10 11 12 from multiprocessing import Processimport osdef run_proc () : """子进程要执行的代码""" print('子进程运行中,pid=%d...' % os.getpid()) print('子进程将要结束...' ) if __name__ == '__main__' : print('父进程pid: %d' % os.getpid()) p = Process(target=run_proc) p.start()
Process语法结构 Process([group [, target [, name [, args [, kwargs]]]]])
target:如果传递了函数的引用,可以任务这个子进程就执行这里的代码
args:给target指定的函数传递的参数,以元组的方式传递
kwargs:给target指定的函数传递命名参数
name:给进程设定一个名字,可以不设定
group:指定进程组,大多数情况下用不到
Process创建的实例对象的常用方法:
start():启动子进程实例(创建子进程)
is_alive():判断进程子进程是否还在活着
join([timeout]):是否等待子进程执行结束,或等待多少秒
terminate():不管任务是否完成,立即终止子进程
Process创建的实例对象的常用属性:
name:当前进程的别名,默认为Process-N,N为从1开始递增的整数
pid:当前进程的pid(进程号)
给子进程指定的函数传递参数 demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from multiprocessing import Processimport osfrom time import sleepdef run_proc (name, age, **kwargs) : for i in range(10 ): print('子进程运行中,name= %s,age=%d ,pid=%d...' % (name, age, os.getpid())) print(kwargs) sleep(0.2 ) if __name__=='__main__' : p = Process(target=run_proc, args=('test' ,18 ), kwargs={"m" :20 }) p.start() sleep(1 ) p.terminate() p.join()
ps: 进程间不同享全局变量
线程 vs 进程 : 线程和进程在使用上各有优缺点:线程执行开销小,但不利于资源的管理和保护;而进程正相反。
进程间通信-Queue
可以使用multiprocessing模块的Queue实现多进程之间的数据传递,Queue本身是一个消息列队程序
Queue的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 from multiprocessing import Queueq=Queue(3 ) q.put("消息1" ) q.put("消息2" ) print(q.full()) q.put("消息3" ) print(q.full()) try : q.put("消息4" ,True ,2 ) except : print("消息列队已满,现有消息数量:%s" %q.qsize()) try : q.put_nowait("消息4" ) except : print("消息列队已满,现有消息数量:%s" %q.qsize()) if not q.full(): q.put_nowait("消息4" ) if not q.empty(): for i in range(q.qsize()): print(q.get_nowait())
说明:
初始化Queue()对象时(例如:q=Queue()),若括号中没有指定最大可接收的消息数量,或数量为负值,那么就代表可接受的消息数量没有上限(直到内存的尽头);
Queue.qsize():返回当前队列包含的消息数量;
Queue.empty():如果队列为空,返回True,反之False ;
Queue.full():如果队列满了,返回True,反之False;
Queue.get([block[, timeout]]):获取队列中的一条消息,然后将其从列队中移除,block默认值为True;
1)如果block使用默认值,且没有设置timeout(单位秒),消息列队如果为空,此时程序将被阻塞(停在读取状态),直到从消息列队读到消息为止,如果设置了timeout,则会等待timeout秒,若还没读取到任何消息,则抛出”Queue.Empty”异常;
2)如果block值为False,消息列队如果为空,则会立刻抛出”Queue.Empty”异常;
Queue.get_nowait():相当Queue.get(False);
Queue.put(item,[block[, timeout]]):将item消息写入队列,block默认值为True;
1)如果block使用默认值,且没有设置timeout(单位秒),消息列队如果已经没有空间可写入,此时程序将被阻塞(停在写入状态),直到从消息列队腾出空间为止,如果设置了timeout,则会等待timeout秒,若还没空间,则抛出”Queue.Full”异常;
2)如果block值为False,消息列队如果没有空间可写入,则会立刻抛出”Queue.Full”异常;
Queue.put_nowait(item):相当Queue.put(item, False);
demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 from multiprocessing import Process, Queueimport os, time, randomdef write (q) : for value in ['A' , 'B' , 'C' ]: print('Put %s to queue...' % value) q.put(value) time.sleep(random.random()) def read (q) : while True : if not q.empty(): value = q.get(True ) print('Get %s from queue.' % value) time.sleep(random.random()) else : break if __name__=='__main__' : q = Queue() pw = Process(target=write, args=(q,)) pr = Process(target=read, args=(q,)) pw.start() pw.join() pr.start() pr.join() print('' ) print('所有数据都写入并且读完' )
进程池Pool
当有新的请求提交到Pool中时,如果池还没有满,那么就会创建一个新的进程用来执行该请求;但如果池中的进程数已经达到指定的最大值,那么该请求就会等待,直到池中有进程结束,才会用之前的进程来执行新的任务
demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 from multiprocessing import Poolimport os, time, randomdef worker (msg) : t_start = time.time() print("%s开始执行,进程号为%d" % (msg,os.getpid())) time.sleep(random.random()*2 ) t_stop = time.time() print(msg,"执行完毕,耗时%0.2f" % (t_stop-t_start)) po = Pool(3 ) for i in range(0 ,10 ): po.apply_async(worker,(i,)) print("----start----" ) po.close() po.join() print("-----end-----" )
multiprocessing.Pool常用函数解析:
apply_async(func[, args[, kwds]]) :使用非阻塞方式调用func(并行执行,堵塞方式必须等待上一个进程退出才能执行下一个进程),args为传递给func的参数列表,kwds为传递给func的关键字参数列表;
close():关闭Pool,使其不再接受新的任务;
terminate():不管任务是否完成,立即终止;
join():主进程阻塞,等待子进程的退出, 必须在close或terminate之后使用;
进程池中的Queue
如果要使用Pool创建进程,就需要使用multiprocessing.Manager()中的Queue(),而不是multiprocessing.Queue(),否则会得到的错误信息
demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 from multiprocessing import Manager,Poolimport os,time,randomdef reader (q) : print("reader启动(%s),父进程为(%s)" % (os.getpid(), os.getppid())) for i in range(q.qsize()): print("reader从Queue获取到消息:%s" % q.get(True )) def writer (q) : print("writer启动(%s),父进程为(%s)" % (os.getpid(), os.getppid())) for i in "itcast" : q.put(i) if __name__=="__main__" : print("(%s) start" % os.getpid()) q = Manager().Queue() po = Pool() po.apply_async(writer, (q,)) time.sleep(1 ) po.apply_async(reader, (q,)) po.close() po.join() print("(%s) End" % os.getpid())
协程
协程切换时,因为它自带CPU上下文,只要这个过程中保存或恢复 CPU上下文那么程序还是可以运行的。
协程和线程差异:在实现多任务时, 线程切换从系统层面远不止保存和恢复 CPU上下文这么简单。 操作系统为了程序运行的高效性每个线程都有自己缓存Cache等等数据,操作系统还会帮你做这些数据的恢复操作。 所以线程的切换非常耗性能。但是协程的切换只是单纯的操作CPU的上下文,所以一秒钟切换个上百万次系统都抗的住。
yield 实现切换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import timedef work1 () : while True : print("----work1---" ) yield time.sleep(0.5 ) def work2 () : while True : print("----work2---" ) yield time.sleep(0.5 ) def main () : w1 = work1() w2 = work2() while True : next(w1) next(w2) if __name__ == "__main__" : main()
greenlet
为了更好使用协程来完成多任务,python中的greenlet模块对其封装,从而使得切换任务变的更加简单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 from greenlet import greenletimport timedef test1 () : while True : print("---A--" ) gr2.switch() time.sleep(0.5 ) def test2 () : while True : print("---B--" ) gr1.switch() time.sleep(0.5 ) gr1 = greenlet(test1) gr2 = greenlet(test2) gr1.switch()
gevent
greenlet已经实现了协程,但是这个还的人工切换。python还有一个比greenlet更强大的并且能够自动切换任务的模块gevent
其原理是当一个greenlet遇到IO(指的是input output 输入输出,比如网络、文件操作等)操作时,比如访问网络,就自动切换到其他的greenlet,等到IO操作完成,再在适当的时候切换回来继续执行。
由于IO操作非常耗时,经常使程序处于等待状态,有了gevent为我们自动切换协程,就保证总有greenlet在运行,而不是等待IO
gevent的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 import geventdef f (n) : for i in range(n): print(gevent.getcurrent(), i) g1 = gevent.spawn(f, 5 ) g2 = gevent.spawn(f, 5 ) g3 = gevent.spawn(f, 5 ) g1.join() g2.join() g3.join()
gevent切换执行 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import geventimport timedef f (n) : for i in range(n): print(gevent.getcurrent(), i) gevent.sleep(1 ) g1 = gevent.spawn(f, 5 ) g2 = gevent.spawn(f, 5 ) g3 = gevent.spawn(f, 5 ) g1.join() g2.join() g3.join()
如果使用time.sleep(1), 但是想切换怎么办? 打补丁
给程序打补丁 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from gevent import monkeyimport geventimport randomimport timemonkey.patch_all() def coroutine_work (coroutine_name) : for i in range(10 ): print(coroutine_name, i) time.sleep(random.random()) gevent.joinall([ gevent.spawn(coroutine_work, "work1" ), gevent.spawn(coroutine_work, "work2" ) ])
并发下载原理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 from gevent import monkeyimport geventimport urllib.requestmonkey.patch_all() def my_downLoad (url) : print('GET: %s' % url) resp = urllib.request.urlopen(url) data = resp.read() print('%d bytes received from %s.' % (len(data), url)) gevent.joinall([ gevent.spawn(my_downLoad, 'http://www.baidu.com/' ), gevent.spawn(my_downLoad, 'http://www.itcast.cn/' ), gevent.spawn(my_downLoad, 'http://www.itheima.com/' ), ]) '''运行结果 GET: http://www.baidu.com/ GET: http://www.itcast.cn/ GET: http://www.itheima.com/ 111327 bytes received from http://www.baidu.com/. 172054 bytes received from http://www.itheima.com/. 215035 bytes received from http://www.itcast.cn/. 从上能够看到是先发送的获取baidu的相关信息,然后依次是itcast、itheima,但是收到数据的先后顺序不一定与发送顺序相同,这也就体现出了异步,即不确定什么时候会收到数据,顺序不一定 '''