Skip to content

Instantly share code, notes, and snippets.

@ryukinix
Created April 10, 2016 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryukinix/cfeffad0cb77ed4a179b20d961730b47 to your computer and use it in GitHub Desktop.
Save ryukinix/cfeffad0cb77ed4a179b20d961730b47 to your computer and use it in GitHub Desktop.
Coroutines em Python
#!/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