首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >回调如何工作和全局数据同步

问回调如何工作和全局数据同步
EN

Stack Overflow用户
提问于 2011-11-03 02:44:52
回答 1查看 389关注 0票数 0

我在理解回调和程序流、同步问题上遇到了一些困难。

假设我有一个全局变量g_peers。我用一个系统应用注册了一个回调,它会用- joins/leave/change这样的对等事件通知我。现在在回调中,我正在根据事件和相关信息修改g_peers。在代码的其他部分(即常规代码流),我有从g_peers读取的函数。

现在,这会导致同步问题吗?假设我正在从g_peers中读取数据,这时一个对等点离开了,并且调用了修改g_peers的回调。

回调是如何工作的?在回调结束之前是否会中断正常流程?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-03 02:46:30

多线程环境中的全局变量始终需要同步,以便通过多个线程进行并发访问。

如果您的环境是多线程的,那么回调将在单独的线程中调用,因此必须同步。

如果您的环境是单线程的,则不需要同步。

什么是回调?

简单地说,回调函数是程序员不显式调用的函数。相反,有一些持续等待事件发生的机制,它将调用选定的函数来响应特定事件。

代码语言:javascript
复制
 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.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7985680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档