Python基礎 非同步任務IO asyncio

2021-08-14 02:11:32 字數 1582 閱讀 6452

# main.py

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

# python基礎-非同步io的支援 asyncio

# asyncio的程式設計模型就是乙個訊息迴圈

import threading

import asyncio

# 把 generator 標記為 coroutine 型別,便於執行 eventloop

@asyncio.coroutine

deffunc

(name):

print('start %s! (%s)' % (name, threading.currentthread()))

# yield from語法可以讓我們方便地呼叫另乙個generator

print("%s 延遲 1秒" % name)

r = yield

from asyncio.sleep(1)

elif name == "訪問google":

print("%s 延遲 5秒" % name)

r = yield

from asyncio.sleep(5)

else:

print("%s 延遲 3秒" % name)

r = yield

from asyncio.sleep(3)

print('\n end %s!! (%s)' % (name, threading.currentthread()))

# 獲取 eventloop

loop = asyncio.get_event_loop()

# 執行 coroutine

loop.run_until_complete(asyncio.wait(tasks))

loop.close()

d:\pythonproject\sustudy>python

main.py

start 訪問google

! (<_mainthread(mainthread, started

9292)>)

訪問google 延遲 5秒

start 訪問python

! (<_mainthread(mainthread, started

9292)>)

訪問python 延遲 3秒

9292)>)

! (<_mainthread(mainthread, started

9292)>)

end 訪問python

!! (<_mainthread(mainthread, started

9292)>)

end 訪問google

!! (<_mainthread(mainthread, started

9292)>)

asyncio提供了完善的非同步io支援;

非同步操作需要在coroutine中通過yield from完成;

多個coroutine可以封裝成一組task然後併發執行

非同步io任務 並行執行asyncio yield from coroutine

非同步 非同步任務

非同步任務 記錄一下學習完springboot後進行使用非同步方法時的筆記 service層 author yesijie date 2019 11 29 15 25 service public class asyncc catch interruptedexception e system.ou...

python非同步任務處理框架 celery

celery 是一款非常簡單 靈活 可靠的分布式系統,可用於處理大量訊息,並且提供了一整套操作此系統的一系列工具,同時celery 是一款訊息佇列工具,可用於處理實時資料以及任務排程。比方說現在站點註冊需要在使用者註冊完成後傳送啟用郵件給使用者,而後台傳送郵件時間需要一定時間,而又不能同步等待郵件傳...

python非同步任務佇列示例

很多場景為了不阻塞,都需要非同步 機制。這是乙個簡單的例子,大家參考使用吧 複製 如下 usr bin env python coding utf 8 import logging import queue import threading def func a a,b return a b def...