JavaScript内存模型
是的,我知道在 Javascript 中要求一个正式的内存模型是一项无望的任务,所以我满足于“所有浏览器都遵循这些规则”之类的东西。
我的问题如下:我必须以定义的时间间隔将事件发送到服务器,但这样做时事件可能会添加到我的数组中,即:
function storeEvent(event) {
// may be called at any time
storedEvents.push(event);
}
function broadcastEvents() {
if (storedEvents.length !== 0) {
var eventString = JSON.stringify(storedEvents);
storedEvents = [];
// send eventString to server
}
window.setTimeout(broadcastEvents, BROADCAST_TIMER);
}
那里存在明显的竞争条件,甚至没有考虑丢失的内存屏障。
该怎么办?这里真的缺少 Java 内存模型..
Yes I'm aware that asking for a formal memory model in Javascript is a hopeless undertaking, so I'm settling for "All browsers follow these rules" or something.
My problem is the following: I have to send events in a defined interval to a server, but events may be added to my array while doing so, i.e.:
function storeEvent(event) {
// may be called at any time
storedEvents.push(event);
}
function broadcastEvents() {
if (storedEvents.length !== 0) {
var eventString = JSON.stringify(storedEvents);
storedEvents = [];
// send eventString to server
}
window.setTimeout(broadcastEvents, BROADCAST_TIMER);
}
There's an obvious race condition in there and not even think of the missing memory barriers.
What to do? Really missing the Java memory model here..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有任何竞争条件。
浏览器中的所有 JavaScript 代码都是单线程的。
setTimeout
回调将在 UI 线程上运行,同时不执行任何其他操作。There isn't any race condition.
All JavaScript code in the browser is single-threaded.
The
setTimeout
callback will run on the UI thread while it isn't doing anything else.