17

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
Sanjay D Raju
  • 193
  • 1
  • 1
  • 5

1 Answers1

15

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.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • 2
    So for example i have 2 functions in my main program. 1) FunctionA()-> This is the callback 2)FunctionB() -> this is normal function. Both of these functions can access a global variable. So In this context is a mutex necessary on that variable. Cause the callback can occor at anytime . – Sanjay D Raju Aug 11 '12 at 11:21
  • 3
    @user1592046: Yes. Any concurrent accesses (at least one of which is a write) must be protected by some kind of synchronisation mechanism. If one thread wishes to wait for the other to change the variable, you will also need to use a signalling mechanism such as a semaphore or conditional variable. – Marcelo Cantos Aug 11 '12 at 11:23