Bootstrap

python实现异步操作

方法一

from threading import Thread
from time import sleep


def async_call(func):
    def wrapper(*args, **kwargs):
        thr = Thread(target=func, args=args, kwargs=kwargs)
        thr.start()
    return wrapper

@async_call
def test(ms):
    print("print", ms)
    sleep(ms)
    print("print again", ms)

if __name__ == "__main__":
    for i in range(10):
        test(10 - i)

方法一

import threading
import asyncio


async def hello(ms):
    print("Hello world!", ms)
    await asyncio.sleep(ms)
    print("Hello world again!", ms)

# 获取EventLoop
loop = asyncio.get_event_loop()
tasks = [hello(10), hello(5)]
# 执行coroutine
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
;