同时访问变量 [英] Simultaneous access to variable

查看:32
本文介绍了同时访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从多个回调(事件处理程序)增加全局变量,这些回调可能同时触发.我是否需要担心同时访问该变量?有没有像 C# 中的 Interlocked.Increment 类似的东西?

I need to increment global variable from several callbacks (event handlers), which may fire simultaneously. Do I need to worry about simultaneous access to that variable? Is there any analog of Interlocked.Increment like in C#?

推荐答案

JavaScript 中是否有类似 Interlocked.Increment 的例子?

Is there any analog of Interlocked.Increment in JavaScript?

是的,但您的场景不需要它.¹

Yes, but you don't need it for your scenario.¹

我的意思是我需要从几个不同的回调(事件处理程序)增加全局值,这些回调可能同时触发.

I mean I need to increment global value from several different callbacks (event handlers), which may fire simultaneously.

它们永远不会同时开火.浏览器上的 JavaScript 在每个全局环境中仅运行一个线程(规范将其称为 realm),有时在多个全局环境中共享同一个线程.即使处理程序的事件同时触发或所有处理程序都响应同一事件,对它们的调用也会在任务队列中排队(JS 规范称其为作业队列,HTML 规范称其为任务队列),并且队列一次处理一个任务/作业.

They will never fire simultaneously. JavaScript on browsers runs only a single thread per global environment (the spec calls this a realm), sometimes sharing the same thread across multiple global environments. Even if the handlers' events fire simultaneously or all of the handlers respond to the same event, the calls to them are queued in a task queue (the JS spec calls it a job queue, HTML spec calls it a task queue), and that queue is processed one task/job at a time.

我是否需要担心同时访问该变量?

Do I need to worry about simultaneous access to that variable?

不符合您的情况,不.

¹ 仅供参考:您仅在共享时需要它 SharedArrayBuffer 具有多个线程的实例(在浏览器上,这将通过网络工作者).它是 Atomics.add 并对类型化数组进行操作,该数组可能由 SharedArrayBuffer 支持.

¹ Just for detail: You only need it when sharing SharedArrayBuffer instances with multiple threads (on browsers, that would be via web workers). It's Atomics.add and operates on a typed array, which might be backed by a SharedArrayBuffer.

这篇关于同时访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆