1-1.并行:真的多任务执行(CPU核数>=任务数);即在某个时刻点上,有多个程序同时运行在多个CPU上
1-2.并发:假的多任务执行(CPU核数<任务数);即一段时间内,有多个程序在同一个CPU上运行
2-1.同步:同步是指代码调用IO操作时,必须等待IO操作完成才返回的调用方式
2-2.异步:同步是指代码调用IO操作时,不必等待IO操作完成才返回的调用方式
3-1.阻塞:阻塞是指调用函数时候当前线程被挂起
3-2:非阻塞:非阻塞是指调用函数时候当前线程不会被挂起,而是立即返回
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : 多任务yield-demo2.py # @Author: Liugp # @Date : 2019/6/2 # @Desc : def gen_func(): # 1.可以产出值;2.可以接收值,调用方法传进来的值 try: yield "http://www.baidu.com" except Exception: pass yield 2 yield 3 return "bobby" # 1.生成器不仅可以产出值,还可以接收值 if __name__ == "__main__": gen = gen_func() print(next(gen)) gen.throw(Exception,"download error") print(next(gen)) gen.throw(Exception, "download error")
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : gen_close.py # @Author: Liugp # @Date : 2019/6/2 # @Desc : def gen_func(): # 1.可以产出值;2.可以接收值,调用方法传进来的值 yield "http://www.baidu.com" yield 2 yield 3 return "bobby" # 1.生成器不仅可以产出值,还可以接收值 if __name__ == "__main__": gen = gen_func() print(next(gen)) gen.close() print('bobby')
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : gen_to_coroutine.py.py # @Author: Liugp # @Date : 2019/6/2 # @Desc : # 生成器是可以暂停的函数 import inspect def gen_func(): value = yield 1 return "bobby" if __name__ == "__main__": gen = gen_func() print(inspect.getgeneratorstate(gen)) next(gen) print(inspect.getgeneratorstate(gen)) try: next(gen) except StopIteration: pass print(inspect.getgeneratorstate(gen))
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : yield_from_test.py # @Author: Liugp # @Date : 2019/6/2 # @Desc : from itertools import chain my_list = [1,2,3] my_dict = { 'bobby1':'http://www.baidu.com', 'bobby2':'http://www.taobao.com' } def my_chain(*args,**kwargs): for my_iterable in args: yield from my_iterable # for value in my_iterable: # yield value for value in my_chain(my_list,my_dict,range(5,10)): print(value) def g1(iterable): yield from iterable def main(): g = g1() g.send(None) #1. main调用方g1(委托生成器)gen 子生成器 #2. yield from 会在调用方与子生成器之间建立一个双向通道