Skip to content

Instantly share code, notes, and snippets.

@rking32
Created August 12, 2021 13:05
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 rking32/818bd60a6dd1e632ac61ba6f7e902a5a to your computer and use it in GitHub Desktop.
Save rking32/818bd60a6dd1e632ac61ba6f7e902a5a to your computer and use it in GitHub Desktop.
just some cases for test pyrogram async_to_sync_wrapper
import asyncio
from threading import Thread
from pyrogram import Client, idle
# single threaded
# synchronous main thread style
def sync_(client):
with client:
sync_work(client)
# multi threaded
# synchronous main thread + synchronous thread style
def sync_sync(client):
with client:
t = Thread(target=sync_work, args=(client,), daemon=True)
t.start()
idle()
t.join()
# multi threaded
# synchronous main thread + asynchronous thread style
def sync_async(client):
with client:
t = Thread(target=run, args=(async_work(client),), daemon=True)
t.start()
idle()
t.join()
# single threaded
# asynchronous main thread style
async def async_(client):
async with client:
await async_work(client)
# multi threaded
# asynchronous main thread + synchronous thread style
async def async_sync(client):
async with client:
t = Thread(target=sync_work, args=(client,), daemon=True)
t.start()
await idle()
t.join()
# multi threaded
# asynchronous main thread + asynchronous thread style
async def async_async(client):
async with client:
t = Thread(target=run, args=(async_work(client),), daemon=True)
t.start()
await idle()
t.join()
def run(coro):
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(coro)
finally:
loop.close()
def sync_work(client):
print(client.get_me())
async def async_work(client):
print(await client.get_me())
if __name__ == '__main__':
c = Client(...)
# sync_(c) # works fine
# sync_sync(c) # no output (RuntimeWarning: coroutine 'idle' was never awaited)
# sync_async(c) # no error, no output (just hang)
# run(async_(c)) # works fine
# run(async_sync(c)) # works fine
# run(async_async(c)) # no error, no output (just hang)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment