asyncio 初学笔记

协程

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/7/28 0028 上午 9:30
# @Author  : watermelon
# @File    : test3.py
# @Software: PyCharm
import aiohttp
import asyncio
import datetime
import os
async def create_task(i):
   start = datetime.datetime.now()
   print("this is {id} beginning. time is :{start}".format(id=i,start=start))
   await asyncio.sleep(4)
   print(os.getpid())
   end = datetime.datetime.now()
   print("this is {id} beginning. time is :{end}".format(id=i,end=end))
   return start

async def main():
   start = datetime.datetime.now()
   print("start is :"+str(start))
   task=[create_task(i) for i in range(5)]
   end = datetime.datetime.now()
   print("end is :" + str(end))
   await asyncio.wait(task)

if __name__=='__main__':
   loop=asyncio.new_event_loop() ##创建寻黄
   loop.run_until_complete(main()) ##让创建的5个任务并发进行
   loop.close()

运行结果如下:

start is :2020-07-28 10:15:16.694545
end is :2020-07-28 10:15:16.694545
this is 1 beginning. time is :2020-07-28 10:15:16.694545
this is 3 beginning. time is :2020-07-28 10:15:16.694545
this is 4 beginning. time is :2020-07-28 10:15:16.694545
this is 0 beginning. time is :2020-07-28 10:15:16.694545
this is 2 beginning. time is :2020-07-28 10:15:16.694545
10768
this is 1 beginning. time is :2020-07-28 10:15:20.694783
10768
this is 4 beginning. time is :2020-07-28 10:15:20.694783
10768
this is 2 beginning. time is :2020-07-28 10:15:20.694783
10768
this is 3 beginning. time is :2020-07-28 10:15:20.694783
10768
this is 0 beginning. time is :2020-07-28 10:15:20.694783

Process finished with exit code 0

你可能感兴趣的:(asyncio 初学笔记)