Simultaneous access to variable

我的梦境 提交于 2021-02-05 06:18:28

问题


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#?


回答1:


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.

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?

Not in your scenario, no.


¹ 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.




回答2:


Any client-side JavaScript code is synchronous by default. Events are pushed onto an event queue and processed in a single-threaded event loop. Therefore, you don't need to be concerned with race conditions. Refer to e.g. https://medium.com/@kvosswinkel/is-javascript-synchronous-or-asynchronous-what-the-hell-is-a-promise-7aa9dd8f3bfb.

The only exception to this is when you start using web workers. In this case you may take a look at Atomics (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics), for example.



来源:https://stackoverflow.com/questions/52411476/simultaneous-access-to-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!