Created
July 30, 2022 15:49
-
-
Save graingert/120e3f9c9d9616897ca7c00d55ecfb85 to your computer and use it in GitHub Desktop.
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
from twisted.internet import defer | |
import curio | |
import concurrent | |
class Interceptor: | |
def __init__(self, send, coro): | |
self._send = send | |
self._coro = coro | |
def send(self, v): | |
defer.Deferred.fromCoroutine(self._coro) | |
raise StopIteration("became twisted") | |
async def become_twisted(): | |
task = await curio.current_task() | |
task.send = Interceptor(send=task.send, coro=task.coro).send | |
await curio.current_task() | |
return | |
def hide_call_stack(fn): | |
with concurrent.futures.ThreadPoolExecutor(1) as tpe: | |
tpe.submit(fn).result() | |
class InterdimensionalQueue: | |
def __init__(self): | |
self._q = curio.UniversalQueue() | |
def put(self, v): | |
hide_call_stack(lambda: self._q.put(v)) | |
async def get(self): | |
return await self._q.get() | |
############################################################################## | |
async def wacky(d, u): | |
await curio.sleep(0.1) | |
print("async def wacky is curio") | |
await become_twisted() | |
print("async def wacky became twisted") | |
print(await d) | |
u.callback("hello from twisted") | |
async def call_d_soon(d): | |
await curio.sleep(0.5) | |
d.callback("hello from curio") | |
async def main(): | |
q = InterdimensionalQueue() | |
u = defer.Deferred() | |
u.addCallback(q.put) | |
d = defer.Deferred() | |
t1 = await curio.spawn(wacky, d, u) | |
t2 = await curio.spawn(call_d_soon, d) | |
await t1.join() | |
await t2.join() | |
print(await q.get()) | |
if __name__ == "__main__": | |
curio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment