简体   繁体   English

异步调用如何在更新同一个 state 存储变量时避免冲突?

[英]How do asynchronous calls avoid collisions when updating the same state store variable?

I have a variable called sum=0 then I have a loop that executes asynchronous function 2000 times, each one will return a value.我有一个名为sum=0的变量,然后我有一个循环执行异步 function 2000 次,每次都会返回一个值。 I need to sum all the values returned from the 2000 calls into my variable sum.我需要将 2000 次调用返回的所有值加到我的变量总和中。

How can I guarantee that 2 of the 2000 calls won't access the variable sum at the same time and miscalculate the sum?我如何保证 2000 次调用中的 2 次不会同时访问变量 sum 并错误计算总和?

For example:例如:

Current sum : 50
Call X fetches value of : 8
Call Y fetches value of : 10

The 2 calls try to add the values they got to the value sum through sum = sum + returnedValue , in that operation they fetch the current value of sum (for both will be 50) and each of them tries to add their own returnedValue at the same time.这 2 次调用尝试通过sum = sum + returnedValue将他们获得的值添加到值 sum 中,在该操作中他们获取sum的当前值(因为两者都是 50)并且他们每个人都试图returnedValue同时。

So now call X will try to set the value of sum to 58 and call Y will try to set it to 60 (and only one of them will succeed), while the actual value should be 68 .所以现在调用 X 将尝试将sum的值设置为58 ,调用 Y 将尝试将其设置为60 (只有其中一个会成功),而实际值应该是68

How does this case get handled?这个案子如何处理?

You're guaranteed that sum will only be updated by a single thread (never two simultaneously) because JavaScript guarantees that only one single thread can access the realm (loosely: the global environment and the stuff within it) in which your variable exists (directly, or indirectly in a function's environment within that global environment).您保证sum只会由一个线程更新(永远不会同时更新两个线程),因为 JavaScript 保证只有一个线程可以访问变量存在的realm (松散地:全局环境及其中的内容)(直接,或间接地在该全局环境中的函数环境中)。

For Node.js in particular you can find the details here .具体对于 Node.js,您可以在此处找到详细信息。 For browsers, here .对于浏览器, 这里

For a long time, the JavaScript spec was silent on this and so in theory it was down to implementations, but popular implementations (those in browsers and in Node.js) used a single thread when running the JavaScript code within a realm, and doing that dramatically simplifies some kinds of things (such as your concurrent access situation), so the common near-universal practice was codified in the specification.很长一段时间,JavaScript 规范对此保持沉默,因此理论上它取决于实现,但流行的实现(浏览器和 Node.js 中的实现)在 realm 中运行 JavaScript 代码时使用单个线程,并且做这极大地简化了某些事情(例如您的并发访问情况),因此在规范中编纂了常见的近乎普遍的做法。 (Which proved a very useful precursor to the subsequent addition of shared memory — memory shared between realms and thus, potentially, between threads.) (这被证明是随后添加共享 memory — memory 在领域之间共享并因此可能在线程之间共享的非常有用的先驱。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM