I am having some difficulty understanding callbacks and program flow, synchronization issues.
Lets say I have a global variable g_peers. And I register a callback with a system app which will notify me with peer events like – joins/leave/change. Now in the callback, I am modifying g_peers based on the event and associated information. In other parts of the code (i.e the regular code flow) I have functions which read from g_peers.
Now will this result in synchronization issues? Lets say I am in the middle of reading from g_peers when a peer leaves and callback is invoked which modifies g_peers.
How does callback work? Is the normal flow interrupted till the callback finishes?
Global variables in a multithreaded enviornment always need to be synchronized for concurrent access through multiple threads.
If your environment is multithreaded then the callback will be called in a separate thread and hence must be synchronized.
If your environment is single threaded then no synchronization is needed.
What is a Callback?
In simple terms, a Callback function is one that is not called explicitly by the programmer. Instead, there is some mechanism that continually waits for events to occur, and it will call selected functions in response to particular events.
This mechanism is typically used when a operation(function) can take long time for execution and the caller of the function does not want to wait till the operation is complete, but does wish to be intimated of the outcome of the operation. Typically, Callback functions help implement such an asynchronous mechanism, wherein the caller registers to get inimated about the result of the time consuming processing and continuous other operations while at a later point of time, the caller gets informed of the result.