浏览器中的JavaScript是否可能发生并发读/写读/写冲突? [英] Is it possible for a concurrent read/write read/write collision in JavaScript in the browser?

查看:359
本文介绍了浏览器中的JavaScript是否可能发生并发读/写读/写冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我正在制作几个(比如四个)ajax调用(使用AngularJS http get,如果这很重要)我希望每次调用回调并增加一个计数器,这样我就可以知道什么时候全部(四个)线程已经完成。

I have a situation where I am making several (say four) ajax calls (using AngularJS http get, if that matters) and I want each call to callback and increment a counter, so I can know when all (four) of the threads have completed.

我担心的是,因为JavaScript没有任何可与Java的synchronized或volatile关键字相媲美的东西,所以它可以用于多个并发线程在递增计数器时发生碰撞,从而错过了一些增量。

My concern is that since JavaScript does not have anything comparable to Java's "synchronized" or "volatile" keywords, that it would be possible for multiple concurrent threads to collide while incrementing a counter, thereby missing some increments.

换句话说,两个线程同时出现,并且都读取计数器,得到相同的值(例如100)。然后两个线程递增该计数器(到101)并存储新值,不料,我们错过了一个计数(101而不是102)!

In other words, two threads come at the same time, and both read the counter, getting the same value (for example 100). Then both threads increment that counter (to 101) and store the new value, and behold, we missed a count (101 instead of 102)!

我知道JavaScript是应该是单线程的,但也有例外。

I know that JavaScript is supposed to be single threaded, but there are exceptions.

浏览器中是否存在这种情况,如果是这样,有什么方法可以防范它吗?

Is this situation possible in the browser, and if so, is there any way to guard against it?

推荐答案

不,这是不可能的(不会发生碰撞)。每个AJAX调用响应都可以被视为JavaScript消息队列中的消息。 JavaScript运行时在处理下一个消息之前处理队列中的每个消息。换句话说,它调用事件的回调并运行完整的回调函数(以及它调用的所有函数,依此类推),然后再转到队列中的下一条消息。因此,不会并行处理两个消息(例如,AJAX响应)。

No, it is not possible (no collision will occur). Each AJAX call response can be considered a message on the JavaScript message queue. The JavaScript runtime processes each message on the queue to completion before processing the next. In other words, it calls the callback for the event and runs the full callback function (and all the functions it calls, and so on) to completion before moving onto the next message in the queue. Therefore, no two messages (e.g., AJAX responses) will be processed in parallel.

来源: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop

此外,我在JavaScript工作多年,可以保证这是它的工作原理。

Also, I've worked in JavaScript for many years and can guarantee this is how it works.

这篇关于浏览器中的JavaScript是否可能发生并发读/写读/写冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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