C
C
Coder 14482021-09-12 11:41:58
Python
Coder 1448, 2021-09-12 11:41:58

Should I pass loop to another thread?

The question is purely the nature of "what is the right way." Essence: There is a class in which I need to use telethon's TelegramClient. But I can’t initialize it in one thread and start it in another thread, because even if I supposedly use telethon.sync, it still receives a loop from itself and does everything asynchronously. It turns out that you need to either initialize it in __init__ and pass loop from the first thread to the second as a function argument, or initialize and start in one, second thread, but paycharm swears at this, supposedly everything needs to be initialized in __init__. 2 codes provided below.

Passing a loop to another thread
import asyncio
from threading import Thread

from telethon import TelegramClient


class Binance:
    def __init__(self):
        self.loop = asyncio.get_event_loop()
        self.tg_client = TelegramClient('sess', api_id, api_hash)

    def updating(self, loop):
        asyncio.set_event_loop(loop)

        self.tg_client.start(phone, password)
        print('logged in')


binance = Binance()

updater = Thread(target=binance.updating, args=[binance.loop])
updater.start()

input()


Telethon client initialization in another thread
import asyncio
from threading import Thread

from telethon import TelegramClient


class Binance:
    def __init__(self):
        ...

    def updating(self):
        asyncio.set_event_loop(asyncio.new_event_loop())

        self.tg_client = TelegramClient('sess', api_id, api_hash)  # вот здесь ругается пайчарм
        self.tg_client.start(phone, password)
        print('logged in')


binance = Binance()

updater = Thread(target=binance.updating)
updater.start()

input()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-09-12
@wows15

It's best to avoid thread sharing and async altogether. There are good reasons to combine them, it is better to strive to ensure that each thread has its own event loop, since it is not thread safe.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question