多线程threading和协程

#-*-coding:utf-8-*-
import threading #创建多线程(thread二次封装)
from time import ctime,sleep
import time
def listen(name):
print ('begin listening to {name} {time}'.format(name='shabi',time=ctime()))#类似html的变量,ctime 时间转换成字符串
time.sleep(3)
print ('over {time}'.format(name='shabi',time=ctime()))

def func(name):
print ('{name} running.{time}'.format(name=name,time=ctime()))
time.sleep(5)
print ('{name} running over.{time}'.format(name=name,time=ctime()))

t1=threading.Thread(target=listen,args=('egon',)) #实例化,target执行线程名即函数,args传的参数,要以元祖的形式
t2=threading.Thread(target=func,args=('alex',))
print ('game over {time}'.format(time=ctime()))#主线程必须放在分支线程的start执行前
# t1.start()
# t2.start()
t1.join()#主线程必须等待线程t1执行完
threads=[] #通过列表添加顺序for循环,控制执行顺序,但不能决定谁先执行完
threads.append(t2)
threads.append(t1)
for i in threads:
i.start()#执行命令内部函数





协程(coroutine),又称微线程
  greeenlet 第三方模块,用于实现携程代码(Gevent协程就是基于greenlet)
  yield 生成器,借用生成器的特点也可以实现协程
  asyncio 在python3.4中引入
  async & awiat python3.5中的两个关键字,结合asyncio模块
1. greenlet
  from greenlet import greenlet
  def func1():
    print(1)
    gr2.switch() #切换func2
  def func2():
    print(3)
    gr1.switch() #切换func1
  gr1 = greenlet(func1)
  gr2 = greenlet(func2)

2. yield
  def func1():
    yield 1
    yield from func2() //yield from 是在python3.3引入 类似于切换
    yield 2
  def func2():
    yield 3
  f1 = func1()
  for item in f1:
    print(item)

3.asyncio
  import asyncio
   @asyncio.coroutine
   def func1():
     print(1)
      yield from asyncio.sleep(2)  # 遇到IO耗时操作,自动化切换到tasks中的其他任务
      print(2)
   @asyncio.coroutine
   def func2():
    print(3)
    yield from asyncio.sleep(2# 遇到IO耗时操作,自动化切换到tasks中的其他任务
    print(4)
 
   tasks = [
    asyncio.ensure_future( func1() ),
    asyncio.ensure_future( func2() )
]
   loop = asyncio.get_event_loop()
   loop.run_until_complete(asyncio.wait(tasks))
   注意:基于asyncio模块实现的协程比之前的要更厉害,因为他的内部还集成了遇到IO耗时操作自动切花的功能.
  4.async & await  在python3.5中引入,在python3.8之后@asyncio.coroutine装饰器被移除,使用async & awit代替
    import asyncio
    async def func1():
      await asyncio.sleep(2)
    async def func2():
      await asyncio.sleep(2)
    task = [ asyncio.ensure_future(func1()) ,
      asyncio.ensure_future(func2()) ]
    
    loop = asyncio.get_event_loop()   //创建事件循环
    loop.run_until_complete(asyncio.wait(tasks))  //将协程当做任务提交到事件循环的任务列表,协程执行完成后终止
posted @ 2018-03-31 20:34  coding天荒地老  阅读(231)  评论(0编辑  收藏  举报