python基础(16)-进程&线程&协程

进程之multiprocessing模块

Process(进程)

Process模块是一个创建进程的模块,借助这个模块,就可以完成进程的创建。

  • 介绍
    • 初始化参数
      Process([group [, target [, name [, args [, kwargs]]]]]),由该类实例化得到的对象,表示一个子进程中的任务(尚未启动)
      
      强调:
      1. 需要使用关键字的方式来指定参数
      2. args指定的为传给target函数的位置参数,是一个元组形式,必须有逗号
      
      参数介绍:
      1. group参数未使用,值始终为None
      2. target表示调用对象,即子进程要执行的任务
      3. args表示调用对象的位置参数元组,args=(1,2,'zze',)
      4. kwargs表示调用对象的字典,kwargs={'name':'zze','age':18}
      5. name为子进程的名称
    • 方法
      p.start():启动进程,并调用该子进程中的p.run() 
      p.run():进程启动时运行的方法,正是它去调用target指定的函数,我们自定义类的类中一定要实现该方法  
      p.terminate():强制终止进程p,不会进行任何清理操作,如果p创建了子进程,该子进程就成了僵尸进程,使用该方法需要特别小心这种情况。如果p还保存了一个锁那么也将不会被释放,进而导致死锁
      p.is_alive():如果p仍然运行,返回True
      p.join([timeout]):主线程等待p终止(强调:是主线程处于等的状态,而p是处于运行的状态)。timeout是可选的超时时间,需要强调的是,p.join只能join住start开启的进程,而不能join住run开启的进程  
      
    • 属性
      p.daemon:默认值为False,如果设为True,代表p为后台运行的守护进程,当p的父进程终止时,p也随之终止,并且设定为True后,p不能创建自己的新进程,必须在p.start()之前设置
      p.name:进程的名称
      p.pid:进程的pid
      p.exitcode:进程在运行时为None、如果为–N,表示被信号N结束(了解即可)
      p.authkey:进程的身份验证键,默认是由os.urandom()随机生成的32字符的字符串。这个键的用途是为涉及网络连接的底层进程间通信提供安全性,这类连接只有在具有相同的身份验证键时才能成功(了解即可)
    • 在Windows操作系统中由于没有fork(linux操作系统中创建进程的机制),在创建子进程的时候会自动 import 启动它的这个文件,而在 import 的时候又执行了整个文件。因此如果将process()直接写在文件中就会无限递归创建子进程报错。所以必须把创建子进程的部分使用if __name__ ==‘__main__’ 判断保护起来,import 的时候  ,就不会递归运行了。
  • 使用
    • 创建子进程
       1 import time
       2 from multiprocessing import Process
       3 
       4 
       5 def f(name):
       6     print('hello', name)
       7     print('我是子进程')
       8 
       9 
      10 if __name__ == '__main__':
      11     p = Process(target=f, args=('bob',))
      12     p.start()
      13     time.sleep(1)
      14     print('执行主进程的内容了')
      15 
      16 # result
      17 # hello bob
      18 # 我是子进程
      19 # 执行主进程的内容了
      View Code
    • join()

      join()函数可以阻塞主进程,让其等待子进程代码执行完毕后,再执行join()后面的代码

       1 import time
       2 from multiprocessing import Process
       3 
       4 
       5 def f(name):
       6     print('hello', name)
       7     time.sleep(2)
       8     print('我是子进程')
       9 
      10 
      11 if __name__ == '__main__':
      12     p = Process(target=f, args=('bob',))
      13     p.start()
      14     time.sleep(1)
      15     p.join()
      16     print('执行主进程的内容了')
      17 
      18 # result
      19 # hello bob
      20 # 我是子进程
      21 # 执行主进程的内容了
      View Code
    • 查看进程号
       1 import os
       2 from multiprocessing import Process
       3 
       4 def f(x):
       5     print('子进程id :',os.getpid(),'父进程id :',os.getppid())
       6     return x*x
       7 
       8 if __name__ == '__main__':
       9     print('主进程id :', os.getpid())
      10     p_lst = []
      11     for i in range(5):
      12         p = Process(target=f, args=(i,))
      13         p.start()
      14 
      15 #result:
      16 # 主进程id : 9208
      17 # 子进程id : 4276 父进程id : 9208
      18 # 子进程id : 3744 父进程id : 9208
      19 # 子进程id : 9392 父进程id : 9208
      20 # 子进程id : 3664 父进程id : 9208
      21 # 子进程id : 520 父进程id : 9208
      View Code
    • 执行多个子进程
       1 import time
       2 from multiprocessing import Process
       3 
       4 
       5 def f(name):
       6     print('hello', name)
       7     time.sleep(1)
       8 
       9 
      10 if __name__ == '__main__':
      11     p_lst = []
      12     for i in range(5):
      13         p = Process(target=f, args=('bob%s'%i,))
      14         p.start()
      15         p_lst.append(p)
      16     [p.join() for p in p_lst]
      17     print('父进程在执行')
      18 #result:
      19 # hello bob0
      20 # hello bob1
      21 # hello bob2
      22 # hello bob3
      23 # hello bob4
      24 # 父进程在执行
      View Code
    • 继承Process类开启进程
       1 import os
       2 from multiprocessing import Process
       3 
       4 
       5 class MyProcess(Process):
       6     def __init__(self, name):
       7         super().__init__()
       8         self.name = name
       9 
      10     def run(self):
      11         print(os.getpid())
      12         print(self.name)
      13 
      14 
      15 if __name__ == '__main__':
      16     p1 = MyProcess('p1')
      17     p2 = MyProcess('p2')
      18     p3 = MyProcess('p3')
      19     # start会自动调用run
      20     p1.start()
      21     p2.start()
      22     p3.start()
      23 
      24     p1.join()
      25     p2.join()
      26     p3.join()
      27     print('主线程111')
      28 
      29 #result:
      30 # 1740
      31 # p1
      32 # 8468
      33 # p2
      34 # 9572
      35 # p3
      36 # 主线程111
      View Code
    • 守护进程
       1 import time
       2 from multiprocessing import Process
       3 
       4 
       5 def func():
       6     while True:
       7         print('我还活着')
       8         time.sleep(0.5)
       9 
      10 
      11 if __name__ == "__main__":
      12     p = Process(target=func)
      13     p.daemon = True  # 设置子进程为守护进程
      14     p.start()
      15     i = 2
      16     while i > 0:
      17         print('主进程执行')
      18         time.sleep(1)
      19         i -= 1
      20     print('主进程执行完毕')
      21 
      22 # result
      23 # 主进程执行
      24 # 我还活着
      25 # 我还活着
      26 # 主进程执行
      27 # 我还活着
      28 # 我还活着
      29 # 主进程执行完毕
      守护进程
       1 import time
       2 from multiprocessing import Process
       3 
       4 
       5 def func():
       6     while True:
       7         print('我还活着')
       8         time.sleep(0.5)
       9 
      10 
      11 if __name__ == "__main__":
      12     p = Process(target=func)
      13     # p.daemon = True  # 设置子进程为守护进程
      14     p.start()
      15     i = 2
      16     while i > 0:
      17         print('主进程执行')
      18         time.sleep(1)
      19         i -= 1
      20     print('主进程执行完毕')
      21 
      22 # result
      23 # 主进程执行
      24 # 我还活着
      25 # 我还活着
      26 # 主进程执行
      27 # 我还活着
      28 # 我还活着
      29 # 主进程执行完毕
      30 # 我还活着
      31 # 我还活着
      32 # 我还活着
      33 # 我还活着
      34 # 我还活着
      35 # 我还活着
      36 # 我还活着
      37 # 我还活着
      38 # ...
      非守护进程

Lock(锁)

加锁可以保证代码块在同一时间段只有指定一个进程执行

 1 from multiprocessing import Process
 2 import time
 3 import os
 4 
 5 
 6 def func():
 7     time.sleep(1)
 8     print('正在执行子进程的进程号:{},当前时间:{}'.format(os.getpid(), time.strftime("%Y-%m-%d %X")))
 9 
10 
11 if __name__ == '__main__':
12     for i in range(5):
13         Process(target=func).start()
14 
15 # result:
16 # 正在执行子进程的进程号:6044,当前时间:2018-09-09 19:22:12
17 # 正在执行子进程的进程号:7024,当前时间:2018-09-09 19:22:12
18 # 正在执行子进程的进程号:9900,当前时间:2018-09-09 19:22:12
19 # 正在执行子进程的进程号:8888,当前时间:2018-09-09 19:22:12
20 # 正在执行子进程的进程号:10060,当前时间:2018-09-09 19:22:12
未加锁
 1 from multiprocessing import Lock
 2 from multiprocessing import Process
 3 import time
 4 import os
 5 
 6 
 7 def func(lock):
 8     lock.acquire()
 9     time.sleep(1)
10     print('正在执行子进程的进程号:{},当前时间:{}'.format(os.getpid(), time.strftime("%Y-%m-%d %X")))
11     lock.release()
12 
13 
14 if __name__ == '__main__':
15     lock = Lock()
16     for i in range(5):
17         Process(target=func, args=(lock,)).start()
18 
19 # result:
20 # 正在执行子进程的进程号:8752,当前时间:2018-09-09 19:25:39
21 # 正在执行子进程的进程号:10152,当前时间:2018-09-09 19:25:40
22 # 正在执行子进程的进程号:5784,当前时间:2018-09-09 19:25:41
23 # 正在执行子进程的进程号:9708,当前时间:2018-09-09 19:25:42
24 # 正在执行子进程的进程号:8696,当前时间:2018-09-09 19:25:43
加锁

Semaphore(信号量)

信号量可以保证代码块在同一时间段只有指定数量进程执行

 1 from multiprocessing import Process, Semaphore
 2 import time
 3 
 4 
 5 def func(num, s):
 6     s.acquire()
 7     print('编号:{} 正在执行,'.format(num), time.strftime("%Y-%m-%d %X"))
 8     time.sleep(1)
 9     s.release()
10 
11 
12 if __name__ == '__main__':
13     s = Semaphore(2)
14     for i in range(10):
15         p = Process(target=func, args=(i, s))
16         p.start()
17 
18 # result:
19 # 编号:0 正在执行, 2018-09-10 16:16:28
20 # 编号:1 正在执行, 2018-09-10 16:16:28
21 # 编号:2 正在执行, 2018-09-10 16:16:29
22 # 编号:3 正在执行, 2018-09-10 16:16:29
23 # 编号:4 正在执行, 2018-09-10 16:16:30
24 # 编号:5 正在执行, 2018-09-10 16:16:30
25 # 编号:7 正在执行, 2018-09-10 16:16:31
26 # 编号:6 正在执行, 2018-09-10 16:16:31
27 # 编号:8 正在执行, 2018-09-10 16:16:32
28 # 编号:9 正在执行, 2018-09-10 16:16:32
View Code

Event(事件)

例:让指定代码块在5秒后执行

 1 from multiprocessing import Process, Event
 2 import time
 3 
 4 
 5 # 获取指定秒数后的时间
 6 def get_addsec_time(sec=0):
 7     return time.strftime("%Y-%m-%d %X", time.localtime(time.time() + sec))
 8 
 9 
10 def func(e):
11     print('func准备执行')
12     e.wait()  # 当e.is_set()为True时执行后面代码
13     print('执行了,当前时间:{}'.format(time.strftime("%Y-%m-%d %X")))
14 
15 
16 if __name__ == '__main__':
17     e = Event()
18     print(e.is_set())  # False 初始是阻塞状态
19     e.set()
20     print(e.is_set())  # True 不阻塞
21     e.clear()
22     print(e.is_set())  # False 恢复阻塞
23     after_five_sec = get_addsec_time(5)  # 5秒后的时间
24     Process(target=func, args=(e,)).start()
25     while True:
26         print('当前时间:{}'.format(time.strftime("%Y-%m-%d %X")))
27         time.sleep(1)
28         if time.strftime("%Y-%m-%d %X") == after_five_sec:
29             print('5秒过去了')
30             e.set()
31             break;
32 
33 # result:
34 # False
35 # True
36 # False
37 # 当前时间:2018-09-10 17:06:37
38 # func准备执行
39 # 当前时间:2018-09-10 17:06:38
40 # 当前时间:2018-09-10 17:06:39
41 # 当前时间:2018-09-10 17:06:40
42 # 当前时间:2018-09-10 17:06:41
43 # 5秒过去了
44 # 执行了,当前时间:2018-09-10 17:06:42
View Code

Queue(队列)

创建共享的进程队列,Queue是多进程安全的队列,可以使用Queue实现多进程之间的数据传递。 

  • 介绍
    • 初始化参数
      Queue([maxsize]) 
      创建共享的进程队列。
      参数 :maxsize是队列中允许的最大项数。如果省略此参数,则无大小限制。
      底层队列使用管道和锁定实现。
    • 方法
      q.get( [ block [ ,timeout ] ] ) 
      返回q中的一个项目。如果q为空,此方法将阻塞,直到队列中有项目可用为止。block用于控制阻塞行为,默认为True. 如果设置为False,将引发Queue.Empty异常(定义在Queue模块中)。timeout是可选超时时间,用在阻塞模式中。如果在制定的时间间隔内没有项目变为可用,将引发Queue.Empty异常。
      
      q.get_nowait( ) 
      同q.get(False)方法。
      
      q.put(item [, block [,timeout ] ] ) 
      将item放入队列。如果队列已满,此方法将阻塞至有空间可用为止。block控制阻塞行为,默认为True。如果设置为False,将引发Queue.Empty异常(定义在Queue库模块中)。timeout指定在阻塞模式中等待可用空间的时间长短。超时后将引发Queue.Full异常。
      
      q.qsize() 
      返回队列中目前项目的正确数量。此函数的结果并不可靠,因为在返回结果和在稍后程序中使用结果之间,队列中可能添加或删除了项目。在某些系统上,此方法可能引发NotImplementedError异常。
      
      
      q.empty() 
      如果调用此方法时 q为空,返回True。如果其他进程或线程正在往队列中添加项目,结果是不可靠的。也就是说,在返回和使用结果之间,队列中可能已经加入新的项目。
      
      q.full() 
      如果q已满,返回为True. 由于线程的存在,结果也可能是不可靠的(参考q.empty()方法)。
      q.close() 
      关闭队列,防止队列中加入更多数据。调用此方法时,后台线程将继续写入那些已入队列但尚未写入的数据,但将在此方法完成时马上关闭。如果q被垃圾收集,将自动调用此方法。关闭队列不会在队列使用者中生成任何类型的数据结束信号或异常。例如,如果某个使用者正被阻塞在get()操作上,关闭生产者中的队列不会导致get()方法返回错误。
      
      q.cancel_join_thread() 
      不会再进程退出时自动连接后台线程。这可以防止join_thread()方法阻塞。
      
      q.join_thread() 
      连接队列的后台线程。此方法用于在调用q.close()方法后,等待所有队列项被消耗。默认情况下,此方法由不是q的原始创建者的所有进程调用。调用q.cancel_join_thread()方法可以禁止这种行为。
  • 使用
    • 队列用法
       1 '''
       2 multiprocessing模块支持进程间通信的两种主要形式:管道和队列
       3 都是基于消息传递实现的,但是队列接口
       4 '''
       5 
       6 from multiprocessing import Queue
       7 q=Queue(3)
       8 
       9 #put ,get ,put_nowait,get_nowait,full,empty
      10 q.put(3)
      11 q.put(3)
      12 q.put(3)
      13 # q.put(3)   # 如果队列已经满了,程序就会停在这里,等待数据被别人取走,再将数据放入队列。
      14            # 如果队列中的数据一直不被取走,程序就会永远停在这里。
      15 try:
      16     q.put_nowait(3) # 可以使用put_nowait,如果队列满了不会阻塞,但是会因为队列满了而报错。
      17 except: # 因此我们可以用一个try语句来处理这个错误。这样程序不会一直阻塞下去,但是会丢掉这个消息。
      18     print('队列已经满了')
      19 
      20 # 因此,我们再放入数据之前,可以先看一下队列的状态,如果已经满了,就不继续put了。
      21 print(q.full()) #满了
      22 
      23 print(q.get())
      24 print(q.get())
      25 print(q.get())
      26 # print(q.get()) # 同put方法一样,如果队列已经空了,那么继续取就会出现阻塞。
      27 try:
      28     q.get_nowait(3) # 可以使用get_nowait,如果队列满了不会阻塞,但是会因为没取到值而报错。
      29 except: # 因此我们可以用一个try语句来处理这个错误。这样程序不会一直阻塞下去。
      30     print('队列已经空了')
      31 
      32 print(q.empty()) #空了
      View Code
    • 子进程与主进程通行
       1 from multiprocessing import Process, Queue
       2 
       3 
       4 def func(q, e):
       5     q.put('from son process')
       6 
       7 
       8 if __name__ == '__main__':
       9     q = Queue(5)  # 初始化队列容量为5
      10     p = Process(target=func, args=(q))
      11     p.start()
      12     p.join()
      13     print(q.get())  # from son process
      View Code

JoinableQueue(可连接队列)

创建可连接的共享进程队列。这就像是一个Queue对象,但队列允许项目的使用者通知生产者项目已经被成功处理。通知进程是使用共享的信号和条件变量来实现的。

  • 介绍
    • 方法
      JoinableQueue的实例q除了与Queue对象相同的方法之外,还具有以下方法:
      
      q.task_done() 
      使用者使用此方法发出信号,表示q.get()返回的项目已经被处理。如果调用此方法的次数大于从队列中删除的项目数量,将引发ValueError异常。
      
      q.join() 
      生产者将使用此方法进行阻塞,直到队列中所有项目均被处理。阻塞将持续到为队列中的每个项目均调用q.task_done()方法为止。 
      下面的例子说明如何建立永远运行的进程,使用和处理队列上的项目。生产者将项目放入队列,并等待它们被处理。
  • 使用
    • 生产者和消费者模型
       1 from multiprocessing import JoinableQueue, Process
       2 import time
       3 import random
       4 
       5 
       6 def producer(name, q):
       7     for i in range(1, 11):
       8         time.sleep(random.randint(1, 2))
       9         s = '{}生产的第{}个苹果'.format(name, i)
      10         q.put(s)
      11         print(s)
      12     q.join()  # 生产完毕,使用此方法进行阻塞,直到队列中所有苹果都被吃完。
      13 
      14 
      15 def consumer(name, q):
      16     while True:
      17         time.sleep(random.randint(2, 3))
      18         s = q.get()
      19         print('{}吃了{}'.format(name, s))
      20         q.task_done()  # 向q.join()发送一次信号,证明一个数据已经被取走了
      21 
      22 
      23 if __name__ == '__main__':
      24     q = JoinableQueue(10)
      25     producer_task = Process(target=producer, args=('bob', q))
      26     producer_task.start()
      27     consumer_task = Process(target=consumer, args=('tom', q))
      28     consumer_task.daemon = True  # 设置为守护进程 随主进程代码执行完而结束
      29     consumer_task.start()
      30 
      31     producer_task.join()  # 等待至生产完且生产的苹果都被吃完时继续执行即主进程代码结束
      32 
      33 # result:
      34 # bob生产的第1个苹果
      35 # tom吃了bob生产的第1个苹果
      36 # bob生产的第2个苹果
      37 # tom吃了bob生产的第2个苹果
      38 # bob生产的第3个苹果
      39 # tom吃了bob生产的第3个苹果
      40 # bob生产的第4个苹果
      41 # tom吃了bob生产的第4个苹果
      42 # bob生产的第5个苹果
      43 # tom吃了bob生产的第5个苹果
      44 # bob生产的第6个苹果
      45 # bob生产的第7个苹果
      46 # tom吃了bob生产的第6个苹果
      47 # bob生产的第8个苹果
      48 # tom吃了bob生产的第7个苹果
      49 # bob生产的第9个苹果
      50 # bob生产的第10个苹果
      51 # tom吃了bob生产的第8个苹果
      52 # tom吃了bob生产的第9个苹果
      53 # tom吃了bob生产的第10个苹果
      View Code

Pipe(管道)

  • 介绍
    • 初始化参数
      #创建管道的类:(管道是进程不安全的)
      Pipe([duplex]):在进程之间创建一条管道,并返回元组(conn1,conn2),其中conn1,conn2表示管道两端的连接对象,强调一点:必须在产生Process对象之前产生管道
      #参数介绍:
      dumplex:默认管道是全双工的,如果将duplex设成False,conn1只能用于接收,conn2只能用于发送。
    • 方法
      #主要方法:
      conn1.recv():接收conn2.send(obj)发送的对象。如果没有消息可接收,recv方法会一直阻塞。如果连接的另外一端已经关闭,那么recv方法会抛出EOFError。
      conn1.send(obj):通过连接发送对象。obj是与序列化兼容的任意对象
      #其他方法:
      conn1.close():关闭连接。如果conn1被垃圾回收,将自动调用此方法
      conn1.fileno():返回连接使用的整数文件描述符
      conn1.poll([timeout]):如果连接上的数据可用,返回True。timeout指定等待的最长时限。如果省略此参数,方法将立即返回结果。如果将timeout射成None,操作将无限期地等待数据到达。
       
      conn1.recv_bytes([maxlength]):接收c.send_bytes()方法发送的一条完整的字节消息。maxlength指定要接收的最大字节数。如果进入的消息,超过了这个最大值,将引发IOError异常,并且在连接上无法进行进一步读取。如果连接的另外一端已经关闭,再也不存在任何数据,将引发EOFError异常。
      conn.send_bytes(buffer [, offset [, size]]):通过连接发送字节数据缓冲区,buffer是支持缓冲区接口的任意对象,offset是缓冲区中的字节偏移量,而size是要发送字节数。结果数据以单条消息的形式发出,然后调用c.recv_bytes()函数进行接收    
       
      conn1.recv_bytes_into(buffer [, offset]):接收一条完整的字节消息,并把它保存在buffer对象中,该对象支持可写入的缓冲区接口(即bytearray对象或类似的对象)。offset指定缓冲区中放置消息处的字节位移。返回值是收到的字节数。如果消息长度大于可用的缓冲区空间,将引发BufferTooShort异常。
  • 使用
    • 初使用
       1 from multiprocessing import Process, Pipe
       2 
       3 
       4 def f(conn):
       5     conn.send("from sub process")
       6     conn.close()
       7 
       8 
       9 if __name__ == '__main__':
      10     parent_conn, child_conn = Pipe()
      11     p = Process(target=f, args=(child_conn,))
      12     p.start()
      13     print(parent_conn.recv())  # from sub process
      14     p.join()
      View Code
    • 引发EOFError

      应该特别注意管道端点的正确管理问题。如果是生产者或消费者中都没有使用管道的某个端点,就应将它关闭。这也说明了为何在生产者中关闭了管道的输出端,在消费者中关闭管道的输入端。如果忘记执行这些步骤,程序可能在消费者中的recv()操作上挂起。管道是由操作系统进行引用计数的,必须在所有进程中关闭管道后才能生成EOFError异常。因此,在生产者中关闭管道不会有任何效果,除非消费者也关闭了相同的管道端点。

       1 from multiprocessing import Process, Pipe
       2 
       3 
       4 def f(child_conn):
       5     while True:
       6         try:
       7             print(child_conn.recv())
       8         except EOFError:
       9             child_conn.close()
      10             break
      11 
      12 
      13 if __name__ == '__main__':
      14     parent_conn, child_conn = Pipe()
      15     p = Process(target=f, args=(child_conn,))
      16     p.start()
      17     child_conn.close()
      18     parent_conn.send('hello')
      19     parent_conn.close()
      20     p.join()
      View Code

Manager

 1 from multiprocessing import Manager, Process, Lock
 2 
 3 
 4 def work(d, lock):
 5     # with lock:
 6         d['count'] -= 1
 7 
 8 
 9 if __name__ == '__main__':
10     with Manager() as m:
11         lock = Lock()
12         dic = m.dict({'count': 100})
13         p_l = []
14         for i in range(10):
15             p = Process(target=work, args=(dic, lock))
16             p_l.append(p)
17             p.start()
18         for p in p_l: p.join()
19 
20         print(dic)  # {'count': 91} 
21 # Manager包装的类型是进程不安全的
使用

Pool(进程池)

  • 介绍
    • 初始化参数
      Pool([numprocess  [,initializer [, initargs]]]):创建进程池
      numprocess:要创建的进程数,如果省略,将默认使用cpu_count()的值
      initializer:是每个工作进程启动时要执行的可调用对象,默认为None
      initargs:是要传给initializer的参数组
    • 方法
      p.apply(func [, args [, kwargs]]):在一个池工作进程中执行func(*args,**kwargs),然后返回结果。
      '''需要强调的是:此操作并不会在所有池工作进程中并执行func函数。如果要通过不同参数并发地执行func函数,必须从不同线程调用p.apply()函数或者使用p.apply_async()'''
      
      p.apply_async(func [, args [, kwargs]]):在一个池工作进程中执行func(*args,**kwargs),然后返回结果。
      '''此方法的结果是AsyncResult类的实例,callback是可调用对象,接收输入参数。当func的结果变为可用时,将理解传递给callback。callback禁止执行任何阻塞操作,否则将接收其他异步操作中的结果。'''
         
      p.close():关闭进程池,防止进一步操作。如果所有操作持续挂起,它们将在工作进程终止前完成
      
      P.jion():等待所有工作进程退出。此方法只能在close()或teminate()之后调用

       方法apply_async()和map_async()的返回值是AsyncResul的实例obj。实例具有以下方法
       obj.get():返回结果,如果有必要则等待结果到达。timeout是可选的。如果在指定时间内还没有到达,将引发一场。如果远程操作中引发了异常,它将在调用此方法时再次被引发。
       obj.ready():如果调用完成,返回True
       obj.successful():如果调用完成且没有引发异常,返回True,如果在结果就绪之前调用此方法,引发异常
       obj.wait([timeout]):等待结果变为可用。
       obj.terminate():立即终止所有工作进程,同时不执行任何清理或结束任何挂起工作。如果p被垃圾回收,将自动调用此函数

  • 使用
    • 效率对比
       1 from multiprocessing import Pool, Process
       2 import time
       3 
       4 
       5 def func(n):
       6     for i in range(100):
       7         n += i
       8 
       9 
      10 if __name__ == '__main__':
      11     pool = Pool(5)
      12     start = time.time()
      13     pool.map(func, range(100))
      14     print('进程池执行耗时:{}'.format(time.time() - start))
      15     p_list = []
      16     start = time.time()
      17     for i in range(100):
      18         p = Process(target=func, args=(i,))
      19         p.start()
      20         p_list.append(p)
      21     for p in p_list: p.join()
      22     print('多进程执行耗时:{}'.format(time.time() - start))
      23 
      24 # result:
      25     # 进程池执行耗时: 0.24797534942626953
      26     # 多进程执行耗时: 7.359263896942139
      View Code
    • 同步
       1 import os, time
       2 from multiprocessing import Pool
       3 
       4 
       5 def work(n):
       6     print('%s run' % os.getpid())
       7     time.sleep(3)
       8     return n ** 2
       9 
      10 
      11 if __name__ == '__main__':
      12     p = Pool(3)  # 进程池中从无到有创建三个进程,以后一直是这三个进程在执行任务
      13     res_l = []
      14     for i in range(10):
      15         res = p.apply(work, args=(i,))  # 同步调用,直到本次任务执行完毕拿到res,等待任务work执行的过程中可能有阻塞也可能没有阻塞
      16         res_l.append(res)  # 但不管该任务是否存在阻塞,同步调用都会在原地等着
      17     print(res_l)
      18 # result:
      19     # 15940 run
      20     # 16200 run
      21     # 16320 run
      22     # 15940 run
      23     # 16200 run
      24     # 16320 run
      25     # 15940 run
      26     # 16200 run
      27     # 16320 run
      28     # 15940 run
      29     # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
      View Code
    • 异步
       1 import os
       2 import time
       3 import random
       4 from multiprocessing import Pool
       5 
       6 
       7 def work(n):
       8     print('%s run' % os.getpid())
       9     time.sleep(random.random())
      10     return n ** 2
      11 
      12 
      13 if __name__ == '__main__':
      14     p = Pool(3)  # 进程池中从无到有创建三个进程,以后一直是这三个进程在执行任务
      15     res_l = []
      16     for i in range(10):
      17         res = p.apply_async(work, args=(i,))  # 异步运行,根据进程池中有的进程数,每次最多3个子进程在异步执行
      18         # 返回结果之后,将结果放入列表,归还进程,之后再执行新的任务
      19         # 需要注意的是,进程池中的三个进程不会同时开启或者同时结束
      20         # 而是执行完一个就释放一个进程,这个进程就去接收新的任务。
      21         res_l.append(res)
      22 
      23     # 异步apply_async用法:如果使用异步提交的任务,主进程需要使用jion,等待进程池内任务都处理完,然后可以用get收集结果
      24     # 否则,主进程结束,进程池可能还没来得及执行,也就跟着一起结束了
      25     p.close()
      26     p.join()
      27     for res in res_l:
      28         print(res.get())  # 使用get来获取apply_aync的结果,如果是apply,则没有get方法,因为apply是同步执行,立刻获取结果,也根本无需get
      29 
      30 # result:
      31     # 8872 run
      32     # 13716 run
      33     # 11396 run
      34     # 11396 run
      35     # 8872 run
      36     # 13716 run
      37     # 11396 run
      38     # 8872 run
      39     # 13716 run
      40     # 11396 run
      41     # 0
      42     # 1
      43     # 4
      44     # 9
      45     # 16
      46     # 25
      47     # 36
      48     # 49
      49     # 64
      50     # 81
      View Code
    • 回调函数
       1 from multiprocessing import Pool
       2 
       3 
       4 def func(i):
       5     return i * i
       6 
       7 
       8 def callback_func(i):
       9     print(i)
      10 
      11 
      12 if __name__ == '__main__':
      13     pool = Pool(5)
      14     for i in range(1, 11):
      15         pool.apply_async(func, args=(i,), callback=callback_func)
      16     pool.close()
      17     pool.join()
      18 # # result:
      19     # 1
      20     # 4
      21     # 9
      22     # 16
      23     # 25
      24     # 36
      25     # 49
      26     # 64
      27     # 81
      28     # 100
      View Code

线程之threading模块

进程和线程的关系

1)地址空间和其它资源(如打开文件):进程间相互独立,同一进程的各线程间共享。某进程内的线程在其它进程不可见。

2)通信:进程间通信IPC,线程间可以直接读写进程数据段(如全局变量)来进行通信——需要进程同步和互斥手段的辅助,以保证数据的一致性。

3)调度和切换:线程上下文切换比进程上下文切换要快得多。

4)在多线程操作系统中,进程不是一个可执行的实体。

5)进程是资源分配的最小单位,线程是CPU调度的最小单位,每一个进程中至少有一个线程。

Thread(线程)

  • 介绍

    multiprocess模块的完全模仿了threading模块的接口,二者在使用层面,有很大的相似性。

    Thread实例对象的方法
      isAlive(): 返回线程是否活动的。
      getName(): 返回线程名。
      setName(): 设置线程名。
    
    threading模块提供的一些方法:
      threading.currentThread(): 返回当前的线程变量。
      threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
      threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
     1 import threading
     2 import time
     3 
     4 
     5 def func():
     6     print('start sub thread1')
     7     print(threading.currentThread())  # <Thread(sub thread1, started 11832)>
     8     time.sleep(10)
     9     print('end sub thread1')
    10 
    11 
    12 thread = threading.Thread(target=func)
    13 thread.start()
    14 print(thread.is_alive())  # True
    15 print(thread.getName())  # Thread-1
    16 thread.setName('sub thread1')
    17 print(thread.getName())  # sub thread1
    18 print(threading.currentThread())  # <_MainThread(MainThread, started 9708)>
    19 print(threading.enumerate())  # [<_MainThread(MainThread, started 9708)>, <Thread(sub thread1, started 11832)>]
    20 print(threading.activeCount())  # 2
    示例
  • 使用
    • 创建线程
       1 from threading import Thread
       2 
       3 
       4 def func():
       5     print('from sub threading')
       6 
       7 
       8 p = Thread(target=func)
       9 p.start()
      10 p.join()
      11 # result:
      12     # from sub threading
      View Code
    • 继承Thread创建线程
       1 from threading import Thread
       2 
       3 
       4 class MyThread(Thread):
       5     def run(self):
       6         print('from sub thread,threadid:{}'.format(self.ident))
       7 
       8 
       9 my_thread = MyThread()
      10 my_thread.start()
      11 my_thread.join()
      12 
      13 # result:
      14     # from sub thread,threadid:9332
      View Code
    • 数据共享

      同一进程内的线程之间共享进程内的数据

       1 from threading import Thread
       2 
       3 
       4 def func():
       5     global i
       6     i = 1
       7 
       8 
       9 i = 10
      10 thread = Thread(target=func)
      11 thread.start()
      12 thread.join()
      13 print(i)  # 1
      View Code 
    • 守护线程与守护进程的对比

      无论是进程还是线程,都遵循:守护进程/线程会等待主进程/线程运行完毕后被销毁。需要强调的是:运行完毕并非终止运行

      1.对主进程来说,运行完毕指的是主进程代码运行完毕

      2.对主线程来说,运行完毕指的是主线程所在的进程内所有非守护线程统统运行完毕,主线程才算运行完毕

       1 from multiprocessing import Process
       2 import time
       3 
       4 
       5 def notDaemonFunc():
       6     print('start notDaemonFunc')
       7     time.sleep(10)
       8     print('end notDaemonFunc')
       9 
      10 
      11 def daemonFunc():
      12     print('start daemonFunc')
      13     time.sleep(5)
      14     print('end daemonFunc')  # 主进程代码早已执行完毕没机会执行
      15 
      16 
      17 if __name__ == '__main__':
      18     notDaemonProcess = Process(target=notDaemonFunc)
      19     notDaemonProcess.start()
      20     damonProcess = Process(target=daemonFunc)
      21     damonProcess.daemon = True
      22     damonProcess.start()
      23     time.sleep(1)
      24     print('执行完毕')
      25 
      26 # 主进程代码执行完毕时守护进程立马结束
      27 
      28 # result:
      29     # start notDaemonFunc
      30     # start daemonFunc
      31     # 执行完毕
      32     # end notDaemonFunc
      守护进程
       1 from threading import Thread
       2 import time
       3 
       4 
       5 def notDaemonFunc():
       6     print('start notDaemonFunc')
       7     time.sleep(10)
       8     print('end notDaemonFunc')
       9 
      10 
      11 def daemonFunc():
      12     print('start daemonFunc')
      13     time.sleep(5)
      14     print('end daemonFunc')
      15 
      16 
      17 notDaemonThread = Thread(target=notDaemonFunc)
      18 notDaemonThread.start()
      19 damonThread = Thread(target=daemonFunc)
      20 damonThread.daemon = True
      21 damonThread.start()
      22 time.sleep(1)
      23 print('执行完毕')
      24 
      25 # result:
      26     # start notDaemonFunc
      27     # start daemonFunc
      28     # 执行完毕
      29     # end daemonFunc
      30     # end notDaemonFunc
      守护线程

Lock(锁)

  • 同步锁
     1 from threading import Thread
     2 import time
     3 
     4 
     5 def work():
     6     global n
     7     temp = n
     8     time.sleep(0.1)
     9     n = temp - 1
    10 
    11 
    12 if __name__ == '__main__':
    13     n = 100
    14     l = []
    15     for i in range(100):
    16         p = Thread(target=work)
    17         l.append(p)
    18         p.start()
    19     for p in l:
    20         p.join()
    21 
    22     print(n)  # 期望0 但结果可能为99 98
    未加锁
     1 from threading import Thread, Lock
     2 import time
     3 
     4 
     5 def work(lock):
     6     with lock:
     7         global n
     8         temp = n
     9         time.sleep(0.1)
    10         n = temp - 1
    11 
    12 
    13 if __name__ == '__main__':
    14     n = 100
    15     l = []
    16     lock = Lock()
    17     for i in range(100):
    18         p = Thread(target=work, args=(lock,))
    19         l.append(p)
    20         p.start()
    21     for p in l:
    22         p.join()
    23 
    24     print(n)  # 0
    加锁
  • 死锁

    是指两个或两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程

     1 import time
     2 from threading import Thread, Lock
     3 
     4 noodle_lock = Lock()
     5 fork_lock = Lock()
     6 
     7 
     8 def eat1(name):
     9     noodle_lock.acquire()
    10     print('%s 抢到了面条' % name)
    11     time.sleep(1)
    12     fork_lock.acquire()
    13     print('%s 抢到了筷子' % name)
    14     print('%s 吃面' % name)
    15     fork_lock.release()
    16     noodle_lock.release()
    17 
    18 
    19 def eat2(name):
    20     fork_lock.acquire()
    21     print('%s 抢到了筷子' % name)
    22     time.sleep(1)
    23     noodle_lock.acquire()
    24     print('%s 抢到了面条' % name)
    25     print('%s 吃面' % name)
    26     noodle_lock.release()
    27     fork_lock.release()
    28 
    29 
    30 t1 = Thread(target=eat1, args=('tom',))
    31 t2 = Thread(target=eat2, args=('jerry',))
    32 t1.start()
    33 t2.start()
    34 #result:
    35     # tom 抢到了面条
    36     # jerry 抢到了叉子
    吃面例子 
  • 死锁的解决-递归锁

    在Python中为了支持在同一线程中多次请求同一资源,提供了可重入锁RLock。这个RLock内部维护着一个Lock和一个counter变量,counter记录了acquire的次数,从而使得资源可以被多次请求。直到一个线程所有的acquire都被release,其他的线程才能获得资源。

     1 import time
     2 from threading import Thread, RLock
     3 
     4 fork_lock = noodle_lock = RLock()
     5 
     6 
     7 def eat1(name):
     8     noodle_lock.acquire()
     9     print('%s 抢到了面条' % name)
    10     time.sleep(1)
    11     fork_lock.acquire()
    12     print('%s 抢到了筷子' % name)
    13     print('%s 吃面' % name)
    14     fork_lock.release()
    15     noodle_lock.release()
    16 
    17 
    18 def eat2(name):
    19     fork_lock.acquire()
    20     print('%s 抢到了筷子' % name)
    21     time.sleep(1)
    22     noodle_lock.acquire()
    23     print('%s 抢到了面条' % name)
    24     print('%s 吃面' % name)
    25     noodle_lock.release()
    26     fork_lock.release()
    27 
    28 
    29 t1 = Thread(target=eat1, args=('tom',))
    30 t2 = Thread(target=eat2, args=('jerry',))
    31 t1.start()
    32 t2.start()
    33 
    34 # result:
    35     # tom 抢到了面条
    36     # tom 抢到了筷子
    37     # tom 吃面
    38     # jerry 抢到了筷子
    39     # jerry 抢到了面条
    40     # jerry 吃面
    解决吃面问题

Semaphore(信号量)

 1 from threading import Thread, Semaphore
 2 import time
 3 
 4 
 5 def func(num, s):
 6     s.acquire()
 7     print('编号:{} 正在执行,'.format(num), time.strftime("%Y-%m-%d %X"))
 8     time.sleep(1)
 9     s.release()
10 
11 
12 s = Semaphore(2)
13 [Thread(target=func, args=(i, s)).start() for i in range(10)]
14 
15 # result:
16     # 编号:0 正在执行, 2018-09-12 20:33:09
17     # 编号:1 正在执行, 2018-09-12 20:33:09
18     # 编号:2 正在执行, 2018-09-12 20:33:10
19     # 编号:3 正在执行, 2018-09-12 20:33:10
20     # 编号:4 正在执行, 2018-09-12 20:33:11
21     # 编号:5 正在执行, 2018-09-12 20:33:11
22     # 编号:7 正在执行, 2018-09-12 20:33:12
23     # 编号:6 正在执行, 2018-09-12 20:33:12
24     # 编号:9 正在执行, 2018-09-12 20:33:13
25     # 编号:8 正在执行, 2018-09-12 20:33:13
View Code

Event(事件)

 1 from threading import Thread, Event
 2 import time
 3 
 4 
 5 # 获取指定秒数后的时间
 6 def get_addsec_time(sec=0):
 7     return time.strftime("%Y-%m-%d %X", time.localtime(time.time() + sec))
 8 
 9 
10 def func(e):
11     print('func准备执行')
12     e.wait()  # 当e.is_set()为True时执行后面代码
13     print('执行了,当前时间:{}'.format(time.strftime("%Y-%m-%d %X")))
14 
15 
16 e = Event()
17 print(e.is_set())  # False 初始是阻塞状态
18 e.set()
19 print(e.is_set())  # True 不阻塞
20 e.clear()
21 print(e.is_set())  # False 恢复阻塞
22 after_five_sec = get_addsec_time(5)  # 5秒后的时间
23 Thread(target=func, args=(e,)).start()
24 while True:
25     print('当前时间:{}'.format(time.strftime("%Y-%m-%d %X")))
26     time.sleep(1)
27     if time.strftime("%Y-%m-%d %X") == after_five_sec:
28         print('5秒过去了')
29         e.set()
30         break;
31 
32 # result:
33     # False
34     # True
35     # False
36     # func准备执行
37     # 当前时间:2018-09-12 20:37:27
38     # 当前时间:2018-09-12 20:37:28
39     # 当前时间:2018-09-12 20:37:29
40     # 当前时间:2018-09-12 20:37:30
41     # 当前时间:2018-09-12 20:37:31
42     # 5秒过去了
43     # 执行了,当前时间:2018-09-12 20:37:32
View Code

Condition(条件)

使得线程等待,只有满足某条件时,才释放n个线程

Python提供的Condition对象提供了对复杂线程同步问题的支持。Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还提供了wait和notify方法。线程首先acquire一个条件变量,然后判断一些条件。如果条件不满足则wait;如果条件满足,进行一些处理改变条件后,通过notify方法通知其他线程,其他处于wait状态的线程接到通知后会重新判断条件。不断的重复这一过程,从而解决复杂的同步问题。

 1 import threading
 2 
 3 
 4 def run(n):
 5     con.acquire()
 6     print('prepare')
 7     con.wait()
 8     print("run the thread: %s" % n)
 9     con.release()
10 
11 con = threading.Condition()
12 for i in range(5):
13     t = threading.Thread(target=run, args=(i,))
14     t.start()
15 
16 while True:
17     inp = input('>>>')
18     if inp == 'q':
19         break
20     con.acquire()
21     con.notify(int(inp))
22     con.release()
23     print('------------------------')
24 
25 #result:
26     # prepare
27     # prepare
28     # prepare
29     # prepare
30     # prepare
31     # >>>3
32     # ------------------------
33     # run the thread: 2
34     # run the thread: 1
35     # run the thread: 0
36     # >>>3
37     # ------------------------
38     # run the thread: 4
39     # run the thread: 3
40     # >>>q
View Code

Timer(定时器)

指定n秒后执行某个函数

 1 from threading import Timer
 2 import time
 3 
 4 
 5 def func():
 6     print('in func,current time:{}'.format(time.strftime('%X')))
 7 
 8 
 9 print('in main,current time:{}'.format(time.strftime('%X')))
10 # 5秒后执行
11 t = Timer(5, func)
12 t.start()
13 
14 # result:
15     # in main,current time:20:53:52
16     # in func,current time:20:53:57
View Code

扩展

queen模块

在上述threading模块知识点中并没有出现一个和multiprocessing模块中Queen对应的队列,这是因为python本身给我们提供的queen就是线程安全的,而同个进程的线程之间资源是可以共享的,所以我们可以直接使用queen

  • queue.Queue(maxsize=0) 先进先出
     1 import queue
     2 
     3 q=queue.Queue()
     4 q.put('first')
     5 q.put('second')
     6 q.put('third')
     7 
     8 print(q.get())
     9 print(q.get())
    10 print(q.get())
    11 
    12 '''
    13 result:
    14     first
    15     second
    16     third
    17 '''
    View Code
  • queue.LifoQueue(maxsize=0) 后进先出
     1 import queue
     2 
     3 q = queue.LifoQueue()
     4 q.put('first')
     5 q.put('second')
     6 q.put('third')
     7 
     8 print(q.get())
     9 print(q.get())
    10 print(q.get())
    11 '''
    12 result:
    13     third
    14     second
    15     first
    16 '''
    View Code
  • queue.PriorityQueue(maxsize=0) #优先级
     1 import queue
     2 
     3 q = queue.PriorityQueue()
     4 # put进入一个元组,第一个元素是优先级(通常是数字,也可以是非数字之间的比较),数字越小优先级越高
     5 q.put((20, 'a'))
     6 q.put((10, 'b'))
     7 q.put((30, 'c'))
     8 
     9 print(q.get())
    10 print(q.get())
    11 print(q.get())
    12 '''
    13 数字越小优先级越高,优先级高的优先出队
    14 result:
    15     (10, 'b')
    16     (20, 'a')
    17     (30, 'c')
    18 '''
    View Code

线程池之concurrent.futures模块

  • 介绍
    concurrent.futures模块提供了高度封装的异步调用接口
    ThreadPoolExecutor:线程池,提供异步调用
    ProcessPoolExecutor:进程池,提供异步调用
    
    executor = ProcessPoolExecutor(max_workers=n):初始化进程池 max_workers指定池内最大进程数
    executor.submit(fn, *args, **kwargs):异步提交任务
    executor.map(func, *iterables, timeout=None, chunksize=1) 取代for循环submit的操作
    executor.shutdown(wait=True)  :相当于multiprocessing模块中的pool.close()+pool.join()操作,wait=True时,等待池内所有任务执行完毕回收完资源后才继续.wait=False时,立即返回,并不会等待池内的任务执行完毕,但不管wait参数为何值,整个程序都会等到所有任务执行完毕,submit和map必须在shutdown之前
    executor.submit().result(timeout=None):取得结果
    executor.submit().result(timeout=None):取得结果
    executor.submit().add_done_callback(fn):给任务添加回调函数
  • 使用
    • 创建进程池
       1 from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
       2 
       3 import os, time
       4 
       5 
       6 def func(n):
       7     print('{} is runing ,current time:{}'.format(os.getpid(), time.strftime('%X')))
       8     time.sleep(1)
       9     return 'pid:{} finished'.format(os.getpid())
      10 
      11 
      12 if __name__ == '__main__':
      13     executor = ProcessPoolExecutor(max_workers=2)
      14     result_list = []
      15     for i in range(1, 6):
      16         result = executor.submit(func, i)
      17         result_list.append(result)
      18     executor.shutdown(True)
      19     print('---------------get result-----------------')
      20     for result in result_list:
      21         print(result.result())
      22 
      23 '''
      24 result:
      25     3444 is runing ,current time:21:32:39
      26     2404 is runing ,current time:21:32:39
      27     3444 is runing ,current time:21:32:40
      28     2404 is runing ,current time:21:32:40
      29     3444 is runing ,current time:21:32:41
      30     ---------------get result-----------------
      31     pid:3444 finished
      32     pid:2404 finished
      33     pid:3444 finished
      34     pid:2404 finished
      35     pid:3444 finished
      36 '''
      View Code
    • map使用
       1 from concurrent.futures import ThreadPoolExecutor
       2 import threading
       3 import time
       4 
       5 
       6 def task(n):
       7     print('threadId:{} is runing,current time:{}'.format(threading.currentThread().ident, time.strftime('%X')))
       8     time.sleep(1)
       9     return n ** 2
      10 
      11 
      12 if __name__ == '__main__':
      13     executor = ThreadPoolExecutor(max_workers=2)
      14 
      15     # for i in range(11):
      16     #     future=executor.submit(task,i)
      17 
      18     executor.map(task, range(1, 5))  # map取代了for+submit
      19 
      20 '''
      21 result:
      22     threadId:5324 is runing,current time:21:53:24
      23     threadId:3444 is runing,current time:21:53:24
      24     threadId:5324 is runing,current time:21:53:25
      25     threadId:3444 is runing,current time:21:53:25
      26 '''
      View Code
    • 回调函数
       1 from concurrent.futures import ThreadPoolExecutor
       2 import threading
       3 import time
       4 
       5 
       6 def callback_func(result):
       7     print(result.result())
       8 
       9 
      10 def func(i):
      11     return i * i
      12 
      13 
      14 executor = ThreadPoolExecutor(5)
      15 [executor.submit(func, i).add_done_callback(callback_func) for i in range(1, 5)]
      16 
      17 '''
      18 result:
      19     1
      20     4
      21     9
      22     16
      23 '''
      View Code

协程之gevent模块

单线程里执行多个任务代码通常会既有计算操作又有阻塞操作,我们完全可以在执行任务1时遇到阻塞,就利用阻塞的时间去执行任务2。如此,才能提高效率,这就用到了Gevent模块。

介绍

  • 简介

    协程是单线程下的并发,又称微线程,纤程。英文名Coroutine。一句话说明什么是线程:协程是一种用户态的轻量级线程,即协程是由用户程序自己控制调度的。

    需要强调的是:

    1. python的线程属于内核级别的,即由操作系统控制调度(如单线程遇到io或执行时间过长就会被迫交出cpu执行权限,切换其他线程运行)

    2. 单线程内开启协程,一旦遇到io,就会从应用程序级别(而非操作系统)控制切换,以此来提升效率(!!!非io操作的切换与效率无关) 对比操作系统控制线程的切换,用户在单线程内控制协程的切换

  • 优点

    1. 协程的切换开销更小,属于程序级别的切换,操作系统完全感知不到,因而更加轻量级

    2. 单线程内就可以实现并发的效果,最大限度地利用cpu

  • 缺点

    1. 协程的本质是单线程下,无法利用多核,可以是一个程序开启多个进程,每个进程内开启多个线程,每个线程内开启协程

    2. 协程指的是单个线程,因而一旦协程出现阻塞,将会阻塞整个线程

  • 特点

    1. 必须在只有一个单线程里实现并发

    2. 修改共享数据不需加锁

    3. 用户程序里自己保存多个控制流的上下文栈

    4. 附加:一个协程遇到IO操作自动切换到其它协程(如何实现检测IO,yield、greenlet都无法实现,就用到了gevent模块(select机制))

greenlet模块

安装: pip3 install greenlet 

  • 实现状态切换
     1 from greenlet import greenlet
     2 
     3 
     4 def func1():
     5     print('func1 start')
     6     g2.switch()
     7     print('func1 end')
     8     g2.switch()
     9 
    10 
    11 def func2():
    12     print('func2 start')
    13     g1.switch()
    14     print('func2 end')
    15 
    16 
    17 g1 = greenlet(func1)
    18 g2 = greenlet(func2)
    19 g1.switch()
    20 
    21 '''
    22 result:
    23     func1 start
    24     func2 start
    25     func1 end
    26     func2 end
    27 '''
    View Code
  • 顺序执行与切换执行效率对比
     1 #顺序执行
     2 import time
     3 def f1():
     4     res=1
     5     for i in range(100000000):
     6         res+=i
     7 
     8 def f2():
     9     res=1
    10     for i in range(100000000):
    11         res*=i
    12 
    13 start=time.time()
    14 f1()
    15 f2()
    16 stop=time.time()
    17 print('run time is %s' %(stop-start)) #10.985628366470337
    18 
    19 #切换
    20 from greenlet import greenlet
    21 import time
    22 def f1():
    23     res=1
    24     for i in range(100000000):
    25         res+=i
    26         g2.switch()
    27 
    28 def f2():
    29     res=1
    30     for i in range(100000000):
    31         res*=i
    32         g1.switch()
    33 
    34 start=time.time()
    35 g1=greenlet(f1)
    36 g2=greenlet(f2)
    37 g1.switch()
    38 stop=time.time()
    39 print('run time is %s' %(stop-start)) # 52.763017892837524
    View Code

    单纯的切换(在没有io的情况下或者没有重复开辟内存空间的操作),反而会降低程序的执行速度

协程初使用

安装: pip3 install gevent

  • 非协程和协程耗时对比
     1 import gevent
     2 import threading
     3 import os
     4 import time
     5 
     6 
     7 def func1():
     8     print('pid:{} threadid:{} from func1 | start'.format(os.getpid(), threading.get_ident()))
     9     gevent.sleep(1)
    10     print('pid:{} threadid:{} from func1 | end'.format(os.getpid(), threading.get_ident()))
    11 
    12 
    13 def func2():
    14     print('pid:{} threadid:{} from func2 | start'.format(os.getpid(), threading.get_ident()))
    15     gevent.sleep(1)
    16     print('pid:{} threadid:{} from func2 | end'.format(os.getpid(), threading.get_ident()))
    17 
    18 
    19 start = time.time()
    20 func1()
    21 func2()
    22 print('非协程耗时:{}'.format(time.time() - start))
    23 
    24 start = time.time()
    25 g1 = gevent.spawn(func1)
    26 g2 = gevent.spawn(func2)
    27 g1.join()
    28 g2.join()
    29 print('协程耗时:{}'.format(time.time() - start))
    30 
    31 '''
    32 result:
    33     pid:12092 threadid:2828 from func1 | start
    34     pid:12092 threadid:2828 from func1 | end
    35     pid:12092 threadid:2828 from func2 | start
    36     pid:12092 threadid:2828 from func2 | end
    37     非协程耗时:2.008000135421753
    38     pid:12092 threadid:2828 from func1 | start
    39     pid:12092 threadid:2828 from func2 | start
    40     pid:12092 threadid:2828 from func1 | end
    41     pid:12092 threadid:2828 from func2 | end
    42     协程耗时:1.0
    43 '''
    View Code
  • monkey-识别io阻塞

    上例gevent.sleep(2)模拟的是gevent可以识别的io阻塞,而time.sleep(2)或其他的阻塞,gevent是不能直接识别的需要用下面一行代码,打补丁,就可以识别了

    from gevent import monkey;monkey.patch_all() # 必须放到被打补丁者的前面
     1 from gevent import monkey;monkey.patch_all()
     2 import gevent
     3 import threading
     4 import os
     5 import time
     6 
     7 
     8 def func1():
     9     print('pid:{} threadid:{} from func1 | start'.format(os.getpid(), threading.get_ident()))
    10     time.sleep(1)
    11     print('pid:{} threadid:{} from func1 | end'.format(os.getpid(), threading.get_ident()))
    12 
    13 
    14 def func2():
    15     print('pid:{} threadid:{} from func2 | start'.format(os.getpid(), threading.get_ident()))
    16     time.sleep(1)
    17     print('pid:{} threadid:{} from func2 | end'.format(os.getpid(), threading.get_ident()))
    18 
    19 
    20 start = time.time()
    21 func1()
    22 func2()
    23 print('非协程耗时:{}'.format(time.time() - start))
    24 
    25 start = time.time()
    26 g1 = gevent.spawn(func1)
    27 g2 = gevent.spawn(func2)
    28 g1.join()
    29 g2.join()
    30 print('协程耗时:{}'.format(time.time() - start))
    31 
    32 '''
    33 result:
    34     pid:7200 threadid:43458064 from func1 | start
    35     pid:7200 threadid:43458064 from func1 | end
    36     pid:7200 threadid:43458064 from func2 | start
    37     pid:7200 threadid:43458064 from func2 | end
    38     非协程耗时:2.004999876022339
    39     pid:7200 threadid:55386728 from func1 | start
    40     pid:7200 threadid:55387544 from func2 | start
    41     pid:7200 threadid:55386728 from func1 | end
    42     pid:7200 threadid:55387544 from func2 | end
    43     协程耗时:1.000999927520752
    44 '''
    View Code
  • 统计网页长度
     1 from gevent import monkey;monkey.patch_all()
     2 import gevent
     3 import requests
     4 import time
     5 
     6 
     7 def get_page(url):
     8     print('GET: %s' % url)
     9     response = requests.get(url)
    10     if response.status_code == 200:
    11         print('%d bytes received from %s' % (len(response.text), url))
    12 
    13 
    14 start_time = time.time()
    15 gevent.joinall([
    16     gevent.spawn(get_page, 'https://www.python.org/'),
    17     gevent.spawn(get_page, 'https://www.yahoo.com/'),
    18     gevent.spawn(get_page, 'https://github.com/'),
    19 ])
    20 stop_time = time.time()
    21 print('run time is %s' % (stop_time - start_time))
    22 '''
    23 result:
    24     GET: https://www.python.org/
    25     GET: https://www.yahoo.com/
    26     GET: https://github.com/
    27     64127 bytes received from https://github.com/
    28     48854 bytes received from https://www.python.org/
    29     502701 bytes received from https://www.yahoo.com/
    30     run time is 1.9760000705718994
    31 '''
    View Code
  • 单线程下的socket并发
     1 from gevent import monkey;monkey.patch_all()
     2 from socket import *
     3 import gevent
     4 
     5 
     6 # 如果不想用money.patch_all()打补丁,可以用gevent自带的socket
     7 # from gevent import socket
     8 # s=socket.socket()
     9 
    10 def server(server_ip, port):
    11     s = socket(AF_INET, SOCK_STREAM)
    12     s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    13     s.bind((server_ip, port))
    14     s.listen(5)
    15     while True:
    16         conn, addr = s.accept()
    17         gevent.spawn(talk, conn, addr)
    18 
    19 
    20 def talk(conn, addr):
    21     try:
    22         while True:
    23             res = conn.recv(1024)
    24             print('client %s:%s msg: %s' % (addr[0], addr[1], res))
    25             conn.send(res.upper())
    26     except Exception as e:
    27         print(e)
    28     finally:
    29         conn.close()
    30 
    31 
    32 if __name__ == '__main__':
    33     server('127.0.0.1', 8080)
    server
     1 from threading import Thread
     2 from socket import *
     3 import threading
     4 
     5 
     6 def client(server_ip, port):
     7     c = socket(AF_INET, SOCK_STREAM)  # 套接字对象一定要加到函数内,即局部名称空间内,放在函数外则被所有线程共享,则大家公用一个套接字对象,那么客户端端口永远一样了
     8     c.connect((server_ip, port))
     9 
    10     count = 0
    11     while True:
    12         c.send(('%s say hello %s' % (threading.current_thread().getName(), count)).encode('utf-8'))
    13         msg = c.recv(1024)
    14         print(msg.decode('utf-8'))
    15         count += 1
    16 
    17 
    18 if __name__ == '__main__':
    19     for i in range(500):
    20         t = Thread(target=client, args=('127.0.0.1', 8080))
    21         t.start()
    client

     

转载于:https://www.cnblogs.com/zze46/p/9614671.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值