Created
April 10, 2016 23:36
-
-
Save ryukinix/cfeffad0cb77ed4a179b20d961730b47 to your computer and use it in GitHub Desktop.
Coroutines em Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding=utf-8 | |
# Python Script | |
# | |
# Copyright © Manoel Vilela | |
# | |
# | |
from queue import Queue | |
import asyncio | |
from concurrent.futures import ThreadPoolExecutor | |
replies = Queue() | |
# producer | |
async def ping(): | |
while True: | |
# insere primeiro | |
await loop.run_in_executor(pool, replies.put, "ping") | |
print("ping -> ", replies.get()) # faz get do que vier | |
await asyncio.sleep(0.5) | |
# consumer | |
async def pong(): | |
while True: | |
print("pong -> ", replies.get()) # recebe uma resposta primeiro | |
await loop.run_in_executor(pool, replies.put, "pong") # insere depois | |
await asyncio.sleep(0.5) | |
pool = ThreadPoolExecutor(2) | |
loop = asyncio.get_event_loop() | |
loop.create_task(ping()) | |
loop.create_task(pong()) | |
loop.run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment