asyncioは、Python 3.4で導入された標準ライブラリであり、非同期IOを直接サポートします。
asyncioのプログラミングモデルはメッセージループです。asyncioモジュールからEventLoopへの参照を直接取得し、実行する必要のあるコルーチンをEventLoopにスローして実行すると、非同期IOが実現されます。
次のように、asyncioを使用してHelloworldコードを実装します。
import asyncio
@asyncio.coroutine
def hello():
print('Hello world!')
# 异步调用asyncio.sleep(1):
r = yield from asyncio.sleep(1)
print("Hello again!")
# 获取EventLoop:
loop = asyncio.get_event_loop()
# 执行coroutine
loop.run_until_complete(hello())
loop.close()
@ asyncio.coroutineは、ジェネレーターをコルーチンタイプとしてマークし、このコルーチンをEventLoopにスローして実行します。
hello()はHu Hello worldを最初に出力します!、次に、構文からのyieldにより、別のジェネレーターを簡単に呼び出すことができます。asyncio.sleep()もコルーチンであるため、スレッドはasyncio.sleep()を待機せず、次のメッセージループを直接中断して実行します。asyncio.sleep()が戻ると、スレッドはyieldからの戻り値(ここではNone)を取得し、ステートメントの次の行を実行できます。
asyncio.sleep(1)を1秒かかるIO操作と考えてください。この期間中、メインスレッドは待機せず、EventLoopで他の実行可能コルーチンを実行するため、同時実行を実現できます。
タスクで2つのコルーチンをカプセル化してみましょう:
import threading
import asyncio
@asyncio.coroutine
def hello():
print('Hello world! (%s)' % threading.currentThread())
yield from asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
実行プロセスを観察します。
Hello world! (<_MainThread(MainThread, started 140735195337472)>)
Hello world! (<_MainThread(MainThread, started 140735195337472)>)
(暂停约1秒)
Hello again! (<_MainThread(MainThread, started 140735195337472)>)
Hello again! (<_MainThread(MainThread, started 140735195337472)>)
印刷された現在のスレッド名から、2つのコルーチンが同じスレッドによって同時に実行されていることがわかります。
asyncio.sleep()を実際のIO操作に置き換えると、1つのスレッドで複数のコルーチンを同時に実行できます。
asyncioの非同期ネットワーク接続を使用して、sina、sohu 、および163のホームページを取得します。
import asyncio
@asyncio.coroutine
def wget(host):
print('wget %s...' % host)
connect = asyncio.open_connection(host, 80)
reader, writer = yield from connect
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode('utf-8'))
yield from writer.drain()
while True:
line = yield from reader.readline()
if line == b'\r\n':
break
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
# Ignore the body, close the socket
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
結果は次のとおりです。
wget www.sohu.com...
wget www.sina.com.cn...
wget www.163.com...
(等待一段时间)
(打印出sohu的header)
www.sohu.com header > HTTP/1.1 200 OK
www.sohu.com header > Content-Type: text/html
...
(打印出sina的header)
www.sina.com.cn header > HTTP/1.1 200 OK
www.sina.com.cn header > Date: Wed, 20 May 2015 04:56:33 GMT
...
(打印出163的header)
www.163.com header > HTTP/1.0 302 Moved Temporarily
www.163.com header > Server: Cdn Cache Server V2.0
...
コルーチンを介した1つのスレッドによって3つの接続が同時に完了することがわかります。
概要
asyncioは完全な非同期IOサポートを提供します。
非同期操作は、コルーチンからのyieldを介して完了する必要があります。
複数のコルーチンを一連のタスクにパッケージ化して、同時に実行することができます。
(キー:タスクのグループをカプセル化した後の同時実行)