Discuss / Python / 这样更容易理解一些

这样更容易理解一些

Topic source

学生229

#1 Created at ... [Delete] [Delete and Lock User]
import threading
import asyncio
#在同一个线程里并行执行  异步IO
@asyncio.coroutine
def hello():
    print('Hello world! (%s)' % threading.currentThread())
    yield from asyncio.sleep(5)
    print('Hello again! (%s)' % threading.currentThread())
@asyncio.coroutine
def hi():
    print('Hi! (%s)' % threading.currentThread())
    yield from asyncio.sleep(6)
    print('Hi! (%s)' % threading.currentThread())

loop = asyncio.get_event_loop()
tasks = [hello(), hi()]
loop.run_until_complete(asyncio.wait(tasks))
print('end')
loop.close()

运行结果:

Hello world! (<_MainThread(MainThread, started 139753048471296)>)
Hi! (<_MainThread(MainThread, started 139753048471296)>)
(会等5秒)
Hello again! (<_MainThread(MainThread, started 139753048471296)>)
(会等1秒)
Hi! (<_MainThread(MainThread, started 139753048471296)>)
end

  • 1

Reply