-
-
Save anonymous/c9e4cd54b51e9262ccc6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import os | |
import sys | |
import signal | |
import asyncio | |
import contextlib | |
@contextlib.contextmanager | |
def parallel(processes): | |
pids = [] | |
try: | |
for _ in range(1, processes): | |
pid = os.fork() | |
if pid == 0: | |
try: | |
yield None | |
except SystemExit as e: | |
os._exit(e.code) | |
except BaseException as e: | |
sys.excepthook(e.__class__, e, e.__traceback__) | |
os._exit(1) | |
os._exit(0) | |
yield | |
for p in pids: | |
os.waitpid(p, 0) | |
finally: | |
for p in pids: | |
os.kill(p, signal.SIGKILL) | |
os.waitpid(p) | |
class EchoProtocol (asyncio.Protocol): | |
def connection_made(self, transport): | |
print('new connection @', os.getpid(), self) | |
self.transport = transport | |
def connection_lost(self, exc): | |
print('lost connection @', os.getpid(), self) | |
def data_received(self, data): | |
self.transport.write(data) | |
if __name__ == '__main__': | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(loop.create_server(EchoProtocol, '', 12345)) | |
print('running on localhost:12345') | |
with parallel(4): | |
loop.run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment