I've recently been looking into the go concurrency model to see how it compares to asyncio.
An interesting concept caught my attention: go generators.
| # Common imports | |
| from time import sleep | |
| # Synchronous imports | |
| from concurrent.futures import ThreadPoolExecutor | |
| # Asynchronous imports | |
| # from gevent.threadpool import ThreadPoolExecutor | |
I've recently been looking into the go concurrency model to see how it compares to asyncio.
An interesting concept caught my attention: go generators.
| import asyncio | |
| from functools import wraps | |
| def gogenerator(aiterable=None, buffering=0): | |
| def decorator(aiterable): | |
| @wraps(aiterable) | |
| def wrapper(*args, **kwargs): | |
| return go(aiterable(*args, **kwargs), buffering) | |
| return wrapper |
| import pygame | |
| import random | |
| import imageio | |
| from fractions import gcd | |
| lcm = lambda x, y: x * y // gcd(x, y) | |
| def random_color(): | |
| r = lambda: random.randint(0, 255) |
| """UDP proxy server.""" | |
| import asyncio | |
| class ProxyDatagramProtocol(asyncio.DatagramProtocol): | |
| def __init__(self, remote_address): | |
| self.remote_address = remote_address | |
| self.remotes = {} |
| """Command line interface for monitoring asyncio tasks.""" | |
| import os | |
| import signal | |
| import asyncio | |
| import argparse | |
| import traceback | |
| import linecache | |
| from itertools import count |
| """Fast eratosthenes prime generator with a cached wheel""" | |
| import sys | |
| import time | |
| import operator | |
| from itertools import cycle, chain, accumulate, islice, count | |
| from functools import lru_cache, reduce, partial | |
| from contextlib import contextmanager | |
| CACHE_LEVEL = 5 |
| import itertools | |
| import collections | |
| def run(tasks): | |
| # Prepare | |
| results = {} | |
| count = itertools.count() | |
| queue = collections.deque() | |
| for task in tasks: |
| """Provide high-level UDP endpoints for asyncio. | |
| Example: | |
| async def main(): | |
| # Create a local UDP enpoint | |
| local = await open_local_endpoint('localhost', 8888) | |
| # Create a remote UDP enpoint, pointing to the first one |
| """Provide an executor to run asyncio coroutines in a shadow thread.""" | |
| import asyncio | |
| from threading import Thread | |
| from concurrent.futures import Executor | |
| class AsyncioExecutor(Executor): | |
| def __init__(self): |