Python协程异步处理

import asyncio
import threading
import time


async def work():
    await asyncio.sleep(1)

async def stopLoop():
    event_loop = asyncio.get_event_loop()
    event_loop.stop()

def startLoop(event_loop):
    asyncio.set_event_loop(event_loop)
    event_loop.run_forever()

loop = asyncio.new_event_loop()
thread = threading.Thread(target=startLoop, args=(loop,))
thread.start()

asyncio.run_coroutine_threadsafe(work(), loop)

time.sleep(3)
asyncio.run_coroutine_threadsafe(stopLoop(), loop)
thread.join()

print('end')

你可能感兴趣的:(python,开发语言)