Python之路【第七篇】:线程、进程和协程
Python之路【第七篇】:线程、进程和协程
Python线程
Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#!/usr/bin/env python# -*- coding:utf-8 -*-import threadingimport time def show(arg): time.sleep(1) print 'thread'+str(arg) for i in range(10): t = threading.Thread(target=show, args=(i,)) t.start() print 'main thread stop' |
上述代码创建了10个“前台”线程,然后控制器就交给了CPU,CPU根据指定算法进行调度,分片执行指令。
更多方法:
- start 线程准备就绪,等待CPU调度
- setName 为线程设置名称
- getName 获取线程名称
- setDaemon 设置为后台线程或前台线程(默认)
如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,均停止
如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止 - join 逐个执行每个线程,执行完毕后继续往下执行,该方法使得多线程变得无意义
- run 线程被cpu调度后自动执行线程对象的run方法
自定义线程类
线程锁(Lock、RLock)
由于线程之间是进行随机调度,并且每个线程可能只执行n条执行之后,当多个线程同时修改同一条数据时可能会出现脏数据,所以,出现了线程锁 - 同一时刻允许一个线程执行操作。
未使用锁
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#!/usr/bin/env python#coding:utf-8 import threadingimport time gl_num = 0 lock = threading.RLock() def Func(): lock.acquire() global gl_num gl_num +=1 time.sleep(1) print gl_num lock.release() for i in range(10): t = threading.Thread(target=Func) t.start() |
信号量(Semaphore)
互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,比如厕所有3个坑,那最多只允许3个人上厕所,后面的人只能等里面有人出来了才能再进去。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import threading,timedef run(n): semaphore.acquire() time.sleep(1) print("run the thread: %s" %n) semaphore.release()if __name__ == '__main__': num= 0 semaphore = threading.BoundedSemaphore(5) #最多允许5个线程同时运行 for i in range(20): t = threading.Thread(target=run,args=(i,)) t.start() |
事件(event)
python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法 set、wait、clear。
事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞。
- clear:将“Flag”设置为False
- set:将“Flag”设置为True
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#!/usr/bin/env python# -*- coding:utf-8 -*-import threadingdef do(event): print 'start' event.wait() print 'execute'event_obj = threading.Event()for i in range(10): t = threading.Thread(target=do, args=(event_obj,)) t.start()event_obj.clear()inp = raw_input('input:')if inp == 'true': event_obj.set() |
条件(Condition)
使得线程等待,只有满足某条件时,才释放n个线程
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import threadingdef run(n): con.acquire() con.wait() print("run the thread: %s" %n) con.release()if __name__ == '__main__': con = threading.Condition() for i in range(10): t = threading.Thread(target=run, args=(i,)) t.start() while True: inp = input('>>>') if inp == 'q': break con.acquire() con.notify(int(inp)) con.release() |
Timer
定时器,指定n秒后执行某操作
|
1
2
3
4
5
6
7
8
|
from threading import Timerdef hello(): print("hello, world")t = Timer(1, hello)t.start() # after 1 seconds, "hello, world" will be printed |
Python 进程
|
1
2
3
4
5
6
7
8
9
10
|
from multiprocessing import Processimport threadingimport time def foo(i): print 'say hi',i for i in range(10): p = Process(target=foo,args=(i,)) p.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
|
#方法一,Arrayfrom multiprocessing import Process,Arraytemp = Array('i', [11,22,33,44])def Foo(i): temp[i] = 100+i for item in temp: print i,'----->',itemfor i in range(2): p = Process(target=Foo,args=(i,)) p.start()#方法二:manage.dict()共享数据from multiprocessing import Process,Managermanage = Manager()dic = manage.dict()def Foo(i): dic[i] = 100+i print dic.values()for i in range(2): p = Process(target=Foo,args=(i,)) p.start() p.join() |
类型对应表
Code
当创建进程时(非使用时),共享数据会被拿到子进程中,当进程中执行完毕后,再赋值给原值。
进程锁实例
进程池
进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。
进程池中有两个方法:
- apply
- apply_async
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#!/usr/bin/env python# -*- coding:utf-8 -*-from multiprocessing import Process,Poolimport time def Foo(i): time.sleep(2) return i+100 def Bar(arg): print arg pool = Pool(5)#print pool.apply(Foo,(1,))#print pool.apply_async(func =Foo, args=(1,)).get() for i in range(10): pool.apply_async(func=Foo, args=(i,),callback=Bar) print 'end'pool.close()pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。 |
协程
线程和进程的操作是由程序触发系统接口,最后的执行者是系统;协程的操作则是程序员。
协程存在的意义:对于多线程应用,CPU通过切片的方式来切换线程间的执行,线程切换时需要耗时(保存状态,下次继续)。协程,则只使用一个线程,在一个线程中规定某个代码块执行顺序。
协程的适用场景:当程序中存在大量不需要CPU的操作时(IO),适用于协程;
greenlet
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#!/usr/bin/env python# -*- coding:utf-8 -*-from greenlet import greenletdef test1(): print 12 gr2.switch() print 34 gr2.switch()def test2(): print 56 gr1.switch() print 78gr1 = greenlet(test1)gr2 = greenlet(test2)gr1.switch() |
gevent
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import geventdef foo(): print('Running in foo') gevent.sleep(0) print('Explicit context switch to foo again')def bar(): print('Explicit context to bar') gevent.sleep(0) print('Implicit context switch back to bar')gevent.joinall([ gevent.spawn(foo), gevent.spawn(bar),]) |
遇到IO操作自动切换:
Python之路【第七篇】:线程、进程和协程
Python线程
Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#!/usr/bin/env python# -*- coding:utf-8 -*-import threadingimport time def show(arg): time.sleep(1) print 'thread'+str(arg) for i in range(10): t = threading.Thread(target=show, args=(i,)) t.start() print 'main thread stop' |
上述代码创建了10个“前台”线程,然后控制器就交给了CPU,CPU根据指定算法进行调度,分片执行指令。
更多方法:
- start 线程准备就绪,等待CPU调度
- setName 为线程设置名称
- getName 获取线程名称
- setDaemon 设置为后台线程或前台线程(默认)
如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,均停止
如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止 - join 逐个执行每个线程,执行完毕后继续往下执行,该方法使得多线程变得无意义
- run 线程被cpu调度后自动执行线程对象的run方法
线程锁(Lock、RLock)
由于线程之间是进行随机调度,并且每个线程可能只执行n条执行之后,当多个线程同时修改同一条数据时可能会出现脏数据,所以,出现了线程锁 - 同一时刻允许一个线程执行操作。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#!/usr/bin/env python#coding:utf-8 import threadingimport time gl_num = 0 lock = threading.RLock() def Func(): lock.acquire() global gl_num gl_num +=1 time.sleep(1) print gl_num lock.release() for i in range(10): t = threading.Thread(target=Func) t.start() |
信号量(Semaphore)
互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,比如厕所有3个坑,那最多只允许3个人上厕所,后面的人只能等里面有人出来了才能再进去。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import threading,timedef run(n): semaphore.acquire() time.sleep(1) print("run the thread: %s" %n) semaphore.release()if __name__ == '__main__': num= 0 semaphore = threading.BoundedSemaphore(5) #最多允许5个线程同时运行 for i in range(20): t = threading.Thread(target=run,args=(i,)) t.start() |
事件(event)
python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法 set、wait、clear。
事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞。
- clear:将“Flag”设置为False
- set:将“Flag”设置为True
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#!/usr/bin/env python# -*- coding:utf-8 -*-import threadingdef do(event): print 'start' event.wait() print 'execute'event_obj = threading.Event()for i in range(10): t = threading.Thread(target=do, args=(event_obj,)) t.start()event_obj.clear()inp = raw_input('input:')if inp == 'true': event_obj.set() |
条件(Condition)
使得线程等待,只有满足某条件时,才释放n个线程
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import threadingdef run(n): con.acquire() con.wait() print("run the thread: %s" %n) con.release()if __name__ == '__main__': con = threading.Condition() for i in range(10): t = threading.Thread(target=run, args=(i,)) t.start() while True: inp = input('>>>') if inp == 'q': break con.acquire() con.notify(int(inp)) con.release() |
Timer
定时器,指定n秒后执行某操作
|
1
2
3
4
5
6
7
8
|
from threading import Timerdef hello(): print("hello, world")t = Timer(1, hello)t.start() # after 1 seconds, "hello, world" will be printed |
Python 进程
|
1
2
3
4
5
6
7
8
9
10
|
from multiprocessing import Processimport threadingimport time def foo(i): print 'say hi',i for i in range(10): p = Process(target=foo,args=(i,)) p.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
|
#方法一,Arrayfrom multiprocessing import Process,Arraytemp = Array('i', [11,22,33,44])def Foo(i): temp[i] = 100+i for item in temp: print i,'----->',itemfor i in range(2): p = Process(target=Foo,args=(i,)) p.start()#方法二:manage.dict()共享数据from multiprocessing import Process,Managermanage = Manager()dic = manage.dict()def Foo(i): dic[i] = 100+i print dic.values()for i in range(2): p = Process(target=Foo,args=(i,)) p.start() p.join() |
当创建进程时(非使用时),共享数据会被拿到子进程中,当进程中执行完毕后,再赋值给原值。
进程池
进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。
进程池中有两个方法:
- apply
- apply_async
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#!/usr/bin/env python# -*- coding:utf-8 -*-from multiprocessing import Process,Poolimport time def Foo(i): time.sleep(2) return i+100 def Bar(arg): print arg pool = Pool(5)#print pool.apply(Foo,(1,))#print pool.apply_async(func =Foo, args=(1,)).get() for i in range(10): pool.apply_async(func=Foo, args=(i,),callback=Bar) print 'end'pool.close()pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。 |
协程
线程和进程的操作是由程序触发系统接口,最后的执行者是系统;协程的操作则是程序员。
协程存在的意义:对于多线程应用,CPU通过切片的方式来切换线程间的执行,线程切换时需要耗时(保存状态,下次继续)。协程,则只使用一个线程,在一个线程中规定某个代码块执行顺序。
协程的适用场景:当程序中存在大量不需要CPU的操作时(IO),适用于协程;
greenlet
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#!/usr/bin/env python# -*- coding:utf-8 -*-from greenlet import greenletdef test1(): print 12 gr2.switch() print 34 gr2.switch()def test2(): print 56 gr1.switch() print 78gr1 = greenlet(test1)gr2 = greenlet(test2)gr1.switch() |
gevent
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import geventdef foo(): print('Running in foo') gevent.sleep(0) print('Explicit context switch to foo again')def bar(): print('Explicit context to bar') gevent.sleep(0) print('Implicit context switch back to bar')gevent.joinall([ gevent.spawn(foo), gevent.spawn(bar),]) |
遇到IO操作自动切换:
Python之路【第七篇】:线程、进程和协程的更多相关文章
- Python 线程&进程与协程
Python 的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC语言的一种继承.Py ...
- Python之路(第七篇)Python作用域、匿名函数、函数式编程、map函数、filter函数、reduce函数
一.作用域 return 可以返回任意值例子 def test1(): print("test1") def test(): print("test") ret ...
- Python菜鸟之路:Python基础-线程、进程、协程
上节内容,简单的介绍了线程和进程,并且介绍了Python中的GIL机制.本节详细介绍线程.进程以及协程的概念及实现. 线程 基本使用 方法1: 创建一个threading.Thread对象,在它的初始 ...
- Python之路,Day9 - 线程、进程、协程和IO多路复用
参考博客: 线程.进程.协程: http://www.cnblogs.com/wupeiqi/articles/5040827.html http://www.cnblogs.com/alex3714 ...
- Python之路【第九篇】:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy
Python之路[第九篇]:Python操作 RabbitMQ.Redis.Memcache.SQLAlchemy Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用 ...
- Python开发【第七篇】:面向对象 和 python面向对象进阶篇(下)
Python开发[第七篇]:面向对象 详见:<Python之路[第五篇]:面向对象及相关> python 面向对象(进阶篇) 上一篇<Python 面向对象(初级篇)> ...
- Python之线程、进程和协程
python之线程.进程和协程 目录: 引言 一.线程 1.1 普通的多线程 1.2 自定义线程类 1.3 线程锁 1.3.1 未使用锁 1.3.2 普通锁Lock和RLock 1.3.3 信号量(S ...
- python运维开发(十一)----线程、进程、协程
内容目录: 线程 基本使用 线程锁 自定义线程池 进程 基本使用 进程锁 进程数据共享 进程池 协程 线程 线程使用的两种方式,一种为我们直接调用thread模块上的方法,另一种我们自定义方式 方式一 ...
- Python 线程和进程和协程总结
Python 线程和进程和协程总结 线程和进程和协程 进程 进程是程序执行时的一个实例,是担当分配系统资源(CPU时间.内存等)的基本单位: 进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其 ...
随机推荐
- Think in UML笔记第1章--为什么要UML
1.1 面向过程还是面向对象 面向过程和面向对象都是一种软件技术.例如把面向过程归纳为结构化程序设计.DFD图.ER模型.UC矩阵等,而面向对象则被归纳为继承.封装.多态.复用等具体的技术.事实上,上 ...
- Maven如何手动添加依赖的jar文件到本地Maven仓库
大家肯定遇到过想在pom文件中加入自己开发的依赖包,这些包肯定是不是在Maven仓库(http://repo1.maven.org/maven2/)的.那我们怎么将那些不存在Maven仓库中的包加入到 ...
- Ubuntu下启动Apache的Rewrite功能
在终端中执行 sudo a2enmod rewrite 指令后,即启用了 Mod_rewrite 模块. 另外,也可以通过将 /etc/apache2/mods-available/rewrite.l ...
- Citrix 服务器虚拟化之二十一 桌面虚拟化之部署Provisioning Services
Citrix 服务器虚拟化之二十一 桌面虚拟化之部署Provisioning Services Provisioning Services 是Citrix 出品的一系列虚拟化产品中最核心的一个组件, ...
- plsql如果表和函数等显示不出来
就把用户设为所有用户,所有的东西就会都显示出来了,然后再把用户切换为当前用户和My objects,你想看的东西就全部显示出来了.
- Collection集合List、Set
Collection集合,用来保存一组数据的数据结构. Collection是一个接口,定义了所有集合都应该包含的特征和行为 Collection派生出了两类集合 List和Set List接口:Li ...
- Bmob—移动后端云服务平台
对于个人或者小团队来说,开发一个有网络功能的游戏是一件不容易的事情,必须掌握一门诸如Java/.net/php这类的服务器开发语言. Bmob云服务方便了开发者.Bmob可以给应用软件快速添加一个安全 ...
- iBeacons 资源汇总
从淘宝上购买了iBeacons的开发模块,便开始要熟悉这个技术了. 先来说一下什么是iBeacons iBeacons是苹果在2013年WWDC上推出一项基于蓝牙4.0(Bluetooth LE | ...
- spring获取bean的时候严格区分大小写
如题:spring获取bean的时候严格区分大小写 配置文件helloservice.xml中配置: <dubbo:reference id="IInsurance" int ...
- Ubuntu Qt arm-linux-androideabi-gcc: Command not found
:-1: error: /opt/Qt/android-ndk-r9c/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86/bin/arm- ...