python学习笔记11 ----线程、进程、协程
进程、线程、协程的概念
进程和线程是操作系统中两个很重要的概念,对于一般的程序,可能有若干个进程,每一个进程有若干个同时执行的线程。进程是资源管理的最小单位,线程是程序执行的最小单位(线程可共享同一进程里的所有资源,进程之间则是独立的),线程和进程的操作是由程序触发系统接口,最后的执行者是系统;协程的操作则是程序员。
线程(threading)
线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。
一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。另外,线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不独立拥有系统资源,但它可与同属一个进程的其它线程共享该进程所拥有的全部资源。
一个线程可以创建和撤消另一个线程,同一进程中的多个线程之间可以并发执行。由于线程之间的相互制约,致使线程在运行中呈现出间断性。线程也有就绪、阻塞和运行三种基本状态。就绪状态是指线程具备运行的所有条件,逻辑上可以运行,在等待处理机;运行状态是指线程占有处理机正在运行;阻塞状态是指线程在等待一个事件(如某个信号量),逻辑上不可执行。每一个应用程序都至少有一个进程和一个线程。线程是程序中一个单一的顺序控制流程。在单个程序中同时运行多个线程完成不同的被划分成一块一块的工作,称为多线程。
线程是进程的执行单元,对于大部分程序,只有一个主线程,为了提高效率,有些程序会使用多线程,在系统中所有的线程看起来是同时执行的。
在python中,如果是I/O密集型任务可使用多线程,若是运算密集型任务则不推荐使用多线程,(最好的方法是直接用c语言编写)
GIL
全局解释器锁(Global Interpreter Lock),是计算机程序设计语言解释器(只有cpython解释器中有)用于同步线程的工具,使得任何时刻仅有一个线程在执行,Python的线程是操作系统的原生线程。
在Linux上为pthread,在Windows上为Win thread,完全由操作系统调度线程的执行。一个python解释器进程内有一条主线程,以及多条用户程序的执行线程。即使在多核CPU
平台上,由于GIL的存在,所以禁止多线程的并行执行。

为什么要有GIL? 作为解释型语言,Python的解释器必须做到既安全又高效。我们都知道多线程编程会遇到的问题。解释器要留意的是避免在不同的线程操作内部共享的数据。同时它还要保证在管理用户线程时总是有最大化的计算资源。那么,不同线程同时访问时,数据的保护机制是怎样的呢?答案是解释器全局锁GIL。GIL对诸如当前线程状态和为垃圾回收而用的堆分配对象这样的东西的访问提供着保护。 为什么不能去掉GIL? 首先,在早期的python解释器依赖较多的全局状态,传承下来,使得想要移除当今的GIL变得更加困难。其次,对于程序员而言,仅仅是想要理解它的实现就需要对操作系统设计、多线程编程、C语言、解释器设计和CPython解释器的实现有着非常彻底的理解。 在1999年,针对Python1.5,一个“freethreading”补丁已经尝试移除GIL,用细粒度的锁来代替。然而,GIL的移除给单线程程序的执行速度带来了一定的负面影响。当用单线程执行时,速度大约降低了40%。虽然使用两个线程时在速度上得到了提高,但这个提高并没有随着核数的增加而线性增长。因此这个补丁没有被采纳。 另外,在python的不同解释器实现中,如PyPy就移除了GIL,其执行速度更快(不单单是去除GIL的原因)。然而,我们通常使用的CPython占有着统治地位的使用量,所以,你懂的。 在Python 3.2中实现了一个新的GIL,并且带着一些积极的结果。这是自1992年以来,GIL的一次最主要改变。旧的GIL通过对Python指令进行计数来确定何时放弃GIL。在新的GIL实现中,用一个固定的超时时间来指示当前的线程以放弃这个锁。在当前线程保持这个锁,且当第二个线程请求这个锁的时候,当前线程就会在5ms后被强制释放掉这个锁(这就是说,当前线程每5ms就要检查其是否需要释放这个锁)。当任务是可行的时候,这会使得线程间的切换更加可预测。 GIL对我们有什么影响? 最大的影响是我们不能随意使用多线程。要区分任务场景。 在单核cpu情况下对性能的影响可以忽略不计,多线程多进程都差不多。在多核CPU时,多线程效率较低。GIL对单进程和多进程没有影响。 在实际使用中有什么好的建议? 建议在IO密集型任务中使用多线程,在计算密集型任务中使用多进程。深入研究python的协程机制,你会有惊喜的。
文件执行顺序
创建一个简单的线程


import threading from time import ctime,sleep def music(func): print("start....%s----%s"%(func,ctime())) sleep(4) print("end.....%s----%s"%(func,ctime())) def move(func): print("start.....%s----%s"%(func,ctime())) sleep(8) print("end......%s----%s"%(func,ctime())) t1 = threading.Thread(target=music,args=("音乐",)) t2 = threading.Thread(target=move,args=("电影",)) if __name__ =="__main__": t1.start() t2.start() print("aaaaaaaaaaaaaaa%s"%ctime()) ''' 执行结果: start....音乐----Thu Sep 29 15:56:47 2016 start.....电影----Thu Sep 29 15:56:47 2016 aaaaaaaaaaaaaaaThu Sep 29 15:56:47 2016 end.....音乐----Thu Sep 29 15:56:51 2016 end......电影----Thu Sep 29 15:56:55 2016 '''
线程的更多方法:
- start 线程准备就绪,等待CPU调度
- setName 为线程设置名称
- getName 获取线程名称
- setDaemon 设置为后台线程或前台线程(默认)
如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,均停止
如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止 - join 逐个执行每个线程,执行完毕后继续往下执行,该方法使得多线程变得无意义
- run 线程被cpu调度后自动执行线程对象的run方法
线程锁(Lock、RLock)
CPU执行任务时,在线程之间是进行随机调度的,并且每个线程可能只执行n条代码后就转而执行另外一条线程。由于在一个进程中的多个线程之间是共享资源和数据的,这就容易造成资源抢夺或脏数据,于是就有了锁的概念,限制某一时刻只有一个线程能访问某个指定的数据。
1、未使用锁
import threading import time NUM = 0 def show(): global NUM NUM += 1 name = t.getName() time.sleep(1) # 注意,这行语句的位置很重要,必须在NUM被修改后,否则观察不到脏数据的现象。 print(name, "执行完毕后,NUM的值为: ", NUM) for i in range(5): t = threading.Thread(target=show) t.start() print('main thread stop') 上述代码运行后,结果如下: main thread stop Thread-1 执行完毕后,NUM的值为: 10 Thread-2 执行完毕后,NUM的值为: 10 Thread-4 执行完毕后,NUM的值为: 10 Thread-3 执行完毕后,NUM的值为: 10 Thread-5 执行完毕后,NUM的值为: 10
由此可见,由于线程同时访问一个数据,产生了错误的结果。为了解决这个问题,python在threading模块中定义了几种线程锁类,分别是:
- Lock 普通锁(不可嵌套)
- RLock 普通锁(可嵌套)常用
- Semaphore 信号量
- event 事件
- condition 条件
2、普通锁Lock和RLock
类名:Lock或RLock
普通锁,也叫互斥锁,是独占的,同一时刻只有一个线程被放行。
import time import threading NUM = 10 def func(lock): global NUM lock.acquire() # 让锁开始起作用 NUM -= 1 time.sleep(1) print(NUM) lock.release() # 释放锁 lock = threading.Lock() # 实例化一个锁对象 for i in range(10): t = threading.Thread(target=func, args=(lock,)) # 记得把锁当作参数传递给func参数 t.start()
以上是threading模块的Lock类,它不支持嵌套锁。RLcok类的用法和Lock一模一样,但它支持嵌套,因此我们一般直接使用RLcok类。
3、 信号量(Semaphore)
类名:BoundedSemaphore
这种锁允许一定数量的线程同时更改数据,它不是互斥锁。比如地铁安检,排队人很多,工作人员只允许一定数量的人进入安检区,其它的人继续排队。
import time import threading def run(n): semaphore.acquire() print("run the thread: %s" % n) time.sleep(1) semaphore.release() num = 0 semaphore = threading.BoundedSemaphore(5) # 最多允许5个线程同时运行 for i in range(20): t = threading.Thread(target=run, args=(i,)) t.start()
4、 事件(Event)
类名:Event
事件主要提供了三个方法 set、wait、clear。
事件机制
:全局定义了一个“Flag”,如果“Flag”的值为False,那么当程序执行wait方法时就会阻塞,如果“Flag”值为True,那么wait方法时便不再阻塞。这种锁,类似交通红绿灯(默认是红灯),它属于在红灯的时候一次性阻挡所有线程,在绿灯的时候,一次性放行所有的排队中的线程。
clear:将“Flag”设置为False
set:将“Flag”设置为True
import threading def func(e,i): print(i) e.wait() # 检测当前event是什么状态,如果是红灯,则阻塞,如果是绿灯则继续往下执行。默认是红灯。 print(i+100) event = threading.Event() for i in range(10): t = threading.Thread(target=func, args=(event, i)) t.start() event.clear() # 主动将状态设置为红灯 inp = input(">>>") if inp == "1": event.set() # 主动将状态设置为绿灯
5、 条件(condition)
类名:Condition
该机制会使得线程等待,只有满足某条件时,才释放n个线程。

import threading def condition(): ret = False r = input(">>>") if r == "yes": ret = True return ret def func(conn, i): print(i) conn.acquire() conn.wait_for(condition) # 这个方法接受一个函数的返回值 print(i+100) conn.release() c = threading.Condition() for i in range(10): t = threading.Thread(target=func, args=(c, i,)) t.start() 上面的例子,每输入一次“yes”放行了一个线程。下面这个,可以选择一次放行几个线程。 #!/usr/bin/env python # -*- coding:utf-8 -*- import threading def 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()
6、 定时器(Timer)
定时器,指定n秒后执行某操作。很简单但很使用的东西。
from threading import Timer def hello(): print("hello, world") t = Timer(1, hello) # 表示1秒后执行hello函数 t.start()
7、 队列
通常而言,队列是一种先进先出的数据结构,与之对应的是堆栈这种后进先出的结构。但是在python中,它内置了一个queue模块,它不但提供普通的队列,还提供一些特殊的队列。具体如下:
- queue.Queue :先进先出队列
- queue.LifoQueue :后进先出队列
- queue.PriorityQueue :优先级队列
- queue.deque :双向队列

1. Queue:先进先出队列 这是最常用也是最普遍的队列,先看一个例子。 import queue q = queue.Queue(5) q.put(11) q.put(22) q.put(33) print(q.get()) print(q.get()) print(q.get()) Queue类的参数和方法: maxsize 队列的最大元素个数,也就是queue.Queue(5)中的5。当队列内的元素达到这个值时,后来的元素默认会阻塞,等待队列腾出位置。 def __init__(self, maxsize=0): self.maxsize = maxsize self._init(maxsize) qsize() 获取当前队列中元素的个数,也就是队列的大小 empty() 判断当前队列是否为空,返回True或者False full() 判断当前队列是否已满,返回True或者False put(self, block=True, timeout=None) 往队列里放一个元素,默认是阻塞和无时间限制的。如果,block设置为False,则不阻塞,这时,如果队列是满的,放不进去,就会弹出异常。如果timeout设置为n秒,则会等待这个秒数后才put,如果put不进去则弹出异常。 get(self, block=True, timeout=None) 从队列里获取一个元素。参数和put是一样的意思。 join() 阻塞进程,直到所有任务完成,需要配合另一个方法task_done。 def join(self): with self.all_tasks_done: while self.unfinished_tasks: self.all_tasks_done.wait() task_done() 表示某个任务完成。每一条get语句后需要一条task_done。 import queue q = queue.Queue(5) q.put(11) q.put(22) print(q.get()) q.task_done() print(q.get()) q.task_done() q.join() 2.LifoQueue:后进先出队列 类似于“堆栈”,后进先出。也较常用。 import queue q = queue.LifoQueue() q.put(123) q.put(456) print(q.get()) 上述代码运行结果是:456 3. PriorityQueue:优先级队列 带有权重的队列,每个元素都是一个元组,前面的数字表示它的优先级,数字越小优先级越高,同样的优先级先进先出 q = queue.PriorityQueue() q.put((1,"alex1")) q.put((1,"alex2")) q.put((1,"alex3")) q.put((3,"alex3")) print(q.get()) 4. deque:双向队列 Queue和LifoQueue的“综合体”,双向进出。方法较多,使用复杂,慎用! q = queue.deque() q.append(123) q.append(333) q.appendleft(456) q.pop() q.popleft()
7、 生产者消费者模型

利用多线程和队列可以搭建一个生产者消费者模型,用于处理大并发的服务。
在并发编程中使用生产者和消费者模式能够解决绝大多数并发问题。该模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据的速度。
为什么要使用生产者和消费者模式
在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程。在多线程开发当中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者处理完,才能继续生产数据。同样的道理,如果消费者的处理能力大于生产者,那么消费者就必须等待生产者。为了解决这个问题于是引入了生产者和消费者模式。
什么是生产者消费者模式
生产者消费者模式是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲区,平衡了生产者和消费者的处理能力。
这个阻塞队列就是用来给生产者和消费者解耦的。纵观大多数设计模式,都会找一个第三者出来进行解耦,如工厂模式的第三者是工厂类,模板模式的第三者是模板类。在学习一些设计模式的过程中,如果先找到这个模式的第三者,能帮助我们快速熟悉一个设计模式。

下面是一个简单的厨师做包子,顾客吃包子的例子。 #!/usr/bin/env python # -*- coding:utf-8 -*- import time import queue import threading q = queue.Queue(10) def productor(i): while True: q.put("厨师 %s 做的包子!"%i) time.sleep(2) def consumer(k): while True: print("顾客 %s 吃了一个 %s"%(k,q.get())) time.sleep(1) for i in range(3): t = threading.Thread(target=productor,args=(i,)) t.start() for k in range(10): v = threading.Thread(target=consumer,args=(k,)) v.start()
8、线程池
在使用多线程处理任务时也不是线程越多越好,由于在切换线程的时候,需要切换上下文环境,依然会造成cpu的大量开销。为解决这个问题,线程池的概念被提出来了。预先创建好一个较为优化的数量的线程,让过来的任务立刻能够使用,就形成了线程池。在python中,没有内置的较好的线程池模块,需要自己实现或使用第三方模块。

import queue import time import threading class MyThreadPool: def __init__(self, maxsize=5): self.maxsize = maxsize self._q = queue.Queue(maxsize) for i in range(maxsize): self._q.put(threading.Thread) def get_thread(self): return self._q.get() def add_thread(self): self._q.put(threading.Thread) def task(i, pool): print(i) time.sleep(1) pool.add_thread() pool = MyThreadPool(5) for i in range(100): t = pool.get_thread() obj = t(target=task, args=(i,pool)) obj.start() 上面的例子是把线程类当做元素添加到队列内。实现方法比较糙,每个线程使用后就被抛弃,一开始就将线程开到满,因此性能较差。下面是一个相对好一点的例子: #!/usr/bin/env python # -*- coding:utf-8 -*- import queue import threading import contextlib import time StopEvent = object() # 创建空对象 class ThreadPool(object): def __init__(self, max_num, max_task_num = None): if max_task_num: self.q = queue.Queue(max_task_num) else: self.q = queue.Queue() self.max_num = max_num self.cancel = False self.terminal = False self.generate_list = [] self.free_list = [] def run(self, func, args, callback=None): """ 线程池执行一个任务 :param func: 任务函数 :param args: 任务函数所需参数 :param callback: 任务执行失败或成功后执行的回调函数,回调函数有两个参数1、任务函数执行状态;2、任务函数返回值(默认为None,即:不执行回调函数) :return: 如果线程池已经终止,则返回True否则None """ if self.cancel: return if len(self.free_list) == 0 and len(self.generate_list) < self.max_num: self.generate_thread() w = (func, args, callback,) self.q.put(w) def generate_thread(self): """ 创建一个线程 """ t = threading.Thread(target=self.call) t.start() def call(self): """ 循环去获取任务函数并执行任务函数 """ current_thread = threading.currentThread self.generate_list.append(current_thread) event = self.q.get() while event != StopEvent: func, arguments, callback = event try: result = func(*arguments) success = True except Exception as e: success = False result = None if callback is not None: try: callback(success, result) except Exception as e: pass with self.worker_state(self.free_list, current_thread): if self.terminal: event = StopEvent else: event = self.q.get() else: self.generate_list.remove(current_thread) def close(self): """ 执行完所有的任务后,所有线程停止 """ self.cancel = True full_size = len(self.generate_list) while full_size: self.q.put(StopEvent) full_size -= 1 def terminate(self): """ 无论是否还有任务,终止线程 """ self.terminal = True while self.generate_list: self.q.put(StopEvent) self.q.empty() @contextlib.contextmanager def worker_state(self, state_list, worker_thread): """ 用于记录线程中正在等待的线程数 """ state_list.append(worker_thread) try: yield finally: state_list.remove(worker_thread) # How to use pool = ThreadPool(5) def callback(status, result): # status, execute action status # result, execute action return value pass def action(i): print(i) for i in range(30): ret = pool.run(action, (i,), callback) time.sleep(5) print(len(pool.generate_list), len(pool.free_list)) print(len(pool.generate_list), len(pool.free_list)) # pool.close() # pool.terminate()
进程(progress)
直观的说,进程就是正在执行的程序(python中每一个.py文件都可以看作是一个进程),是多任务操作系统中的基本单元,是包含了程序指令和相关资源的集合。
操作系统隔绝了每个进程可以访问的地址空间,如果进程间想要传递信息,可使用进程间通信或者文件、数据库等方法。 (windows 下进程之间的通信 http://www.360doc.com/content/14/0802/18/3218170_398864589.shtml)
在进程中的调度中,进程之间的切换需要的时间是很多的,为了更好地利用资源共享和节省开销,从进程中演化出了线程这个概念。
1、创建简单的进程
from multiprocessing import Process import threading import time def foo(i): print ('say hi',i)
for i in range(10):
p = Process(target=foo,args=(i,))
p.start()
2、每个进程都有自己独立的数据空间,不同进程之间通常是不能共享数据,创建一个进程需要非常大的开销。
from multiprocessing import Process from multiprocessing import Manager import time li = [] def foo(i): li.append(i) print ('say hi',li) for i in range(10): p = Process(target=foo,args=(i,)) p.start() print( 'ending',li)
运行上面的代码,你会发现列表li在各个进程中只有自己的数据,完全无法共享。想要进程之间进行资源共享可以使用queues/Array/Manager
这三个multiprocess模块提供的类。

2.1 使用Array共享数据 from multiprocessing import Process from multiprocessing import Array def Foo(i,temp): temp[0] += 100 for item in temp: print(i,'----->',item) if __name__ == '__main__': temp = Array('i', [11, 22, 33, 44]) for i in range(2): p = Process(target=Foo, args=(i,temp)) p.start() 对于Array数组类,括号内的“i”表示它内部的元素全部是int类型,而不是指字符i,列表内的元素可以预先指定,也可以指定列表长度。概括的来说就是Array类在实例化的时候就必须指定数组的数据类型和数组的大小,类似temp = Array('i', 5)。对于数据类型有下面的表格对应: 'c': ctypes.c_char, 'u': ctypes.c_wchar, 'b': ctypes.c_byte, 'B': ctypes.c_ubyte, 'h': ctypes.c_short, 'H': ctypes.c_ushort, 'i': ctypes.c_int, 'I': ctypes.c_uint, 'l': ctypes.c_long, 'L': ctypes.c_ulong, 'f': ctypes.c_float, 'd': ctypes.c_double 2.2 使用Manager共享数据 from multiprocessing import Process,Manager def Foo(i,dic): dic[i] = 100+i print(dic.values()) if __name__ == '__main__': manage = Manager() dic = manage.dict() for i in range(10): p = Process(target=Foo, args=(i,dic)) p.start() p.join() Manager比Array要好用一点,因为它可以同时保存多种类型的数据格式。 2.3 使用queues的Queue类共享数据 import multiprocessing from multiprocessing import Process from multiprocessing import queues def foo(i,arg): arg.put(i) print('The Process is ', i, "and the queue's size is ", arg.qsize()) if __name__ == "__main__": li = queues.Queue(20, ctx=multiprocessing) for i in range(10): p = Process(target=foo, args=(i,li,)) p.start() 这里就有点类似上面的队列了。从运行结果里,你还能发现数据共享中存在的脏数据问题。另外,比较悲催的是multiprocessing里还有一个Queue,一样能实现这个功能。
3、 进程锁

为了防止和多线程一样的出现数据抢夺和脏数据的问题,同样需要设置进程锁。与threading类似,在multiprocessing里也有同名的锁类RLock, Lock, Event, Condition, Semaphore,用法都是一样的! from multiprocessing import Process from multiprocessing import queues from multiprocessing import Array from multiprocessing import RLock, Lock, Event, Condition, Semaphore import multiprocessing import time def foo(i,lis,lc): lc.acquire() lis[0] = lis[0] - 1 time.sleep(1) print('say hi',lis[0]) lc.release() if __name__ == "__main__": # li = [] li = Array('i', 1) li[0] = 10 lock = RLock() for i in range(10): p = Process(target=foo,args=(i,li,lock)) p.start()
4、进程池
进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。
进程池中有以下几个主要方法:
- apply:从进程池里取一个进程并执行
- apply_async:apply的异步版本
- terminate:立刻关闭线程池
- join:主进程等待所有子进程执行完毕,必须在close或terminate之后
- close:等待所有进程结束后,才关闭线程池

from multiprocessing import Process,Pool import 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()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。
协程
线程和进程的操作是由程序触发系统接口,最后的执行者是系统,它本质上是操作系统提供的功能。而协程的操作则是程序员指定的,在python中通过yield,人为的实现并发处理。
协程存在的意义:对于多线程应用,CPU通过切片的方式来切换线程间的执行,线程切换时需要耗时。协程,则只使用一个线程,分解一个线程成为多个“微线程”,在一个线程中规定某个代码块的执行顺序。
协程的适用场景:当程序中存在大量不需要CPU的操作时(IO)。
在不需要自己“造轮子”的年代,同样有第三方模块为我们提供了高效的协程,这里介绍一下greenlet和gevent。本质上,gevent是对greenlet的高级封装,因此一般用它就行,这是一个相当高效的模块。
在使用它们之前,需要先安装,可以通过源码,也可以通过pip3。
greenlet

from greenlet import greenlet def test1(): print 12 gr2.switch() print 34 gr2.switch() def test2(): print 56 gr1.switch() print 78 gr1 = greenlet(test1) gr2 = greenlet(test2) gr1.switch()
gevent
gevent 是基于 greenlet 的一个 python 库,它可以把 python 的内置线程用 greenlet 包装,这样在我们使用线程的时候,实际上使用的是协程

import gevent def 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操作自动切换 from gevent import monkey; monkey.patch_all() import gevent import urllib2 def f(url): print('GET: %s' % url) resp = urllib2.urlopen(url) data = resp.read() print('%d bytes received from %s.' % (len(data), url)) gevent.joinall([ gevent.spawn(f, 'https://www.python.org/'), gevent.spawn(f, 'https://www.yahoo.com/'), gevent.spawn(f, 'https://github.com/'), ])
总结
进程拥有自己独立的堆和栈,既不共享堆,亦不共享栈,进程由操作系统调度。
线程拥有自己独立的栈和共享的堆,共享堆,不共享栈,线程亦由操作系统调度(标准线程是的)。
协程和线程一样共享堆,不共享栈,协程由程序员在协程的代码里显示调度。
进程和其他两个的区别还是很明显的。
协程和线程的区别是:协程避免了无意义的调度,由此可以提高性能,但也因此,程序员必须自己承担调度的责任,同时,协程也失去了标准线程使用多CPU的能力。