What's the difference between async methods and streams?

Can someone explain what is the difference between async methods and thread creation in Vala? And where should I use this or that code in my code?

+3


source to share


1 answer


Threads are independently scheduled, whereas methods async

run on the main thread, that is, they are coroutines. For example, if you block reading a socket on a separate thread, the application may continue to run, but if you do so using a method async

, the application will block.

Themes and coroutines (methods async

) can solve some of the same problems, but they usually do different things. In Gtk + (and many other GUIs), only one thread can manipulate GUI objects, and events from GUI objects will only happen on that thread (commonly called the event dispatch thread). If another thread wants to access the GUI elements, it must either a) go through the blocking procedure or b) send a message to the EDT. This summarizes all communication between threads: for communication between threads or to use shared resources, blocking and communication is necessary.

Coroutines are executed in EDT as "just another event". Consider a situation where you have a window with a download button. When the user clicks the button, EDT triggers the click handler associated with the button. If this code were actually trying to download the file, the GUI would hang until the file had finished downloading. If a coroutine has been started, the button handler will run a method async

that will open the socket and then it will be told that it is not ready yet. It then puts the socket and callback in an EDT loop (GLib.MainLoop

). The button handler will exit and the EDT will sit and wait for an event from the X display or socket, then call the correct callback to handle it. This allows GUI events to be interleaved with socket events. However, only one handler can run at a time, so the handlers must be able to shut down quickly or the application will not respond.



Using coroutines becomes a huge mess of callbacks, but the methods async

hide the callbacks so that they look like straightforward code even if they aren't.

If your task is mostly coming to life, then coroutines are the right options. If your task is busy with work, then it will undoubtedly need to enter the flow. Cutroins cannot exceed more than one processor, and threads can run in parallel on multiple processors. GLib coroutines also cannot be easily mixed with threads: it is not wise to try to use methods async

independently on two threads: only EDT uses methods async

.

+8


source







All Articles