I have a general question about a threads and callbacks. Say for example we have a thread running continuously along with the main program.
The main program has registered a callback function with the thread. So the thread can call the callback function at any time. Generally, we register a callback by passing a function pointer to the thread.I want to know when that callback function is called by the thread, will it be a part of that thread or, will it be part of the main program. I want to know the mechanism of this process like how the main program execution is stopped or interrupted when the callback is called by the thread. Another thing is how will the function call stack behave when the callback is called.
One pattern for performing long-running tasks without blocking the main thread is callbacks. By using callbacks, you can start long-running tasks on a background thread. When the task completes, the callback, supplied as an argument, is called to inform your code of the result on the main thread.
Callbacks can be called in the primary thread of a program, interrupting that main program, or they can be called on a different thread so the callback is processed while the main program continues to run. Different programming languages many handle default callbacks in different ways.
If a callback function can be called from multiple threads, then the callback must be thread-safe. Generally, callbacks are called from the thread that provoked the callback event, but some callbacks can be invoked by an internal Client-Library worker thread and execute in the context of the worker thread.
Note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. A good example is the callback functions executed inside a . then() block chained onto the end of a promise after that promise fulfills or rejects.
As a general rule, function calls are always made in the caller's context (thread). It doesn't matter whether the callee is a function, member function, functor object, or anything else.
In other words, when the thread calls your callback, the call happens in the thread. The main thread is not stopped in order to execute the callback. In fact, it isn't involved in any way with the execution of the callback.
Various frameworks provide tricks to make it seem as if one thread can call another directly, but this is always done in a cooperative way through some kind of marshalled message-passing mechanism. Threads generally don't twiddle each other's stacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With