tdlib / td

Cross-platform library for building Telegram clients
https://core.telegram.org/tdlib
Boost Software License 1.0
7.11k stars 1.44k forks source link

How to design a multithreaded application #2778

Closed ghost closed 8 months ago

ghost commented 8 months ago

I have an application that is split into multiple threads: A) UI rendering B) User input C) Sending requests / receiving responses from TDLib I have a class that presents an interface to interact with TDLib via methods like get_authorisation_state, get_chat_list, get_message_list etc and each one sends a request and receives a response. If you try to get the response in more than one thread, an error will occur. How can I implement these methods so that they can be called from different threads (for example, from thread C and thread A)?

levlam commented 8 months ago

I have an application that is split into multiple threads

This splitting is expected from a GUI application.

You can use td_send from any thread, but the way you dispatch response on the same thread depends on the programming language and framework you use. In some programming languages the best way is to use coroutines, in others you can use callbacks and framework-provided way to dispatch events between threads. In any case, you need an asynchronous scheduler provided by the programming language implementation or framework to simplify communication between threads.

ghost commented 8 months ago

My application will have a TUI interface and it is written in C++. I have a separate class for TDLib, in its constructor the TDLib update loop starts. This loop calls the get_authorization_state method, but I need to be able to call it in another thread too.

levlam commented 8 months ago

You must process responses asynchronously, so you need the ability to process response on another thread. Instead of full processing, you can just dispatch response to the original thread, but in any case you need the way to save request context and send data to other threads. For this you need some kind of multithread queues/multithread event dispatcher/multithread scheduler. There are a lot of decent already existing implementations of those, but I can't recommend any particular one.