我在理解回调和程序流、同步问题上遇到了一些困难。
假设我有一个全局变量g_peers。我用一个系统应用注册了一个回调,它会用- joins/leave/change这样的对等事件通知我。现在在回调中,我正在根据事件和相关信息修改g_peers。在代码的其他部分(即常规代码流),我有从g_peers读取的函数。
现在,这会导致同步问题吗?假设我正在从g_peers中读取数据,这时一个对等点离开了,并且调用了修改g_peers的回调。
回调是如何工作的?在回调结束之前是否会中断正常流程?
发布于 2011-11-03 02:46:30
多线程环境中的全局变量始终需要同步,以便通过多个线程进行并发访问。
如果您的环境是多线程的,那么回调将在单独的线程中调用,因此必须同步。
如果您的环境是单线程的,则不需要同步。
什么是回调?
简单地说,回调函数是程序员不显式调用的函数。相反,有一些持续等待事件发生的机制,它将调用选定的函数来响应特定事件。
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.https://stackoverflow.com/questions/7985680
复制相似问题