Created
December 29, 2017 16:18
-
-
Save pitrou/40fcfe893bbf6f843de739ae6555ad07 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
import gc | |
import pprint | |
import types | |
import weakref | |
import asyncio | |
from asyncio import tasks | |
from tornado import gen | |
from tornado.ioloop import IOLoop | |
@gen.coroutine | |
def infinite_coro(holder): | |
print("-- infinite coro started --") | |
try: | |
while True: | |
yield gen.sleep(0.05) | |
finally: | |
print("-- infinite coro finalized! --") | |
async def infinite_task(holder): | |
print("-- infinite task started --") | |
try: | |
while True: | |
#print(" ... infinite task") | |
await gen.sleep(0.05) | |
finally: | |
print("-- infinite task finalized! --") | |
def print_refs(obj): | |
assert obj is not None | |
for r in gc.get_referrers(obj): | |
if isinstance(r, types.FrameType): | |
if r.f_code.co_name != 'print_refs': | |
print(f" - Frame: {r.f_code}") | |
else: | |
print(f" - {r!r}") | |
def main(): | |
ref_cycle = [] | |
wcoro = wtask = None | |
async def do_something(): | |
nonlocal wcoro, wtask | |
loop.add_callback(infinite_coro, ref_cycle) | |
loop.add_callback(infinite_task, ref_cycle) | |
await gen.sleep(0.01) | |
runner,= (r for r in gen._futures_to_runners.values() | |
if 'infinite_coro' in repr(r.gen)) | |
task, = (t for t in tasks.Task.all_tasks() | |
if 'infinite_task' in repr(t)) | |
wcoro = weakref.ref(runner.gen) | |
wtask = weakref.ref(task) | |
await gen.sleep(0.1) | |
loop = IOLoop.current() | |
print("-- starting loop --") | |
loop.run_sync(do_something) | |
loop.close() | |
do_something = loop = ref_cycle = None | |
IOLoop.clear_current() | |
asyncio.get_event_loop().close() # needed to collect the infinite task | |
gc.collect() | |
print("-- loop closed --") | |
print() | |
if wcoro() is None: | |
print("== coro collected! ==") | |
else: | |
print("== coro refs ==") | |
print_refs(wcoro()) | |
print() | |
if wtask() is None: | |
print("== task collected! ==") | |
else: | |
print("== task refs ==") | |
print_refs(wtask()) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment