JavaScript需要互斥吗? [英] Are Mutexes needed in javascript?

查看:106
本文介绍了JavaScript需要互斥吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过以下链接:在JavaScript中实现互斥. 另一方面,我已经读到javascript中没有线程,但是那到底是什么意思呢?

I have seen this link: Implementing Mutual Exclusion in JavaScript. On the other hand, I have read that there are no threads in javascript, but what exactly does that mean?

事件发生时,它们可以在代码中的何处中断?

When events occur, where in the code can they interrupt?

如果JS中没有线程,是否需要在JS中使用互斥锁?

And if there are no threads in JS, do I need to use mutexes in JS or not?

特别是,我想知道使用setTimeout()XmlHttpRequestonreadystatechange调用的函数对全局可访问变量的影响.

Specifically, I am wondering about the effects of using functions called by setTimeout() and XmlHttpRequest's onreadystatechange on globally accessible variables.

推荐答案

Javascript被定义为可重入语言,这意味着没有向用户公开的线程,实现中可能会有线程. setTimeout()和异步回调之类的功能需要等待脚本引擎进入睡眠状态,然后才能运行.

Javascript is defined as a reentrant language which means there is no threading exposed to the user, there may be threads in the implementation. Functions like setTimeout() and asynchronous callbacks need to wait for the script engine to sleep before they're able to run.

这意味着事件中发生的所有事情都必须先完成,然后才能处理下一个事件.

That means that everything that happens in an event must be finished before the next event will be processed.

话虽如此,如果代码在异步事件被触发与调用回调之间不希望其值改变的情况下执行某些操作,则可能需要互斥锁.

That being said, you may need a mutex if your code does something where it expects a value not to change between when the asynchronous event was fired and when the callback was called.

例如,如果您有一个数据结构,在其中单击一个按钮,然后它发送一个XmlHttpRequest来调用回调,则该数据结构将以破坏性的方式更改,而在另一个按钮之间,您将有另一个按钮直接更改相同的数据结构.事件被触发,执行回调时,用户可能在回调之前单击并更新了数据结构,这可能会丢失值.

For example if you have a data structure where you click one button and it sends an XmlHttpRequest which calls a callback the changes the data structure in a destructive way, and you have another button that changes the same data structure directly, between when the event was fired and when the call back was executed the user could have clicked and updated the data structure before the callback which could then lose the value.

尽管您可以创建一个类似竞争的条件,但是很容易在代码中避免这种竞争,因为每个函数都是原子的.实际上,要创建竞争条件将需要大量工作,并且需要一些奇怪的编码模式.

While you could create a race condition like that it's very easy to prevent that in your code since each function will be atomic. It would be a lot of work and take some odd coding patterns to create the race condition in fact.

这篇关于JavaScript需要互斥吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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