开发者

javascript - event driven and concurrency issues?

开发者 https://www.devze.com 2023-01-25 20:30 出处:网络
Greetings, I\'ve been studying javascript, nodejs.And I don\'t understand how the concurrency issues are avoided in javascript.

Greetings,

I've been studying javascript, nodejs. And I don't understand how the concurrency issues are avoided in javascript.

Lets say I'm working on a object

var bigObject = new BigObject();

and I have a setTimer(function(){ workOnBigOjbect...} ) that will also do work on bigOjbect.

If I have disk IO being written into bigObject, and a timer object working on bigObject, and regularly code reading from bigObject, how are concurrency issues avoided?

In a regular language, I would use a mutex or thread-safe queue/command pattern. I also don't see much disc开发者_StackOverflow中文版ussion about race conditions for javascript.

Am I missing something?


The whole point of node.js is that it's event-driven. All the code runs in event handlers in a single thread. There are no concurrency issues because the code doesn't run concurrently. The downside is that each event handler must exit quickly because it blocks the other events.

In your example, the code will start the disk IO and exit immediately. The node.js infrastructure will notify the program that the IO operation was completed by running an event handler. The timer event will be called before or after the IO event, but never concurrently.


Javascript is single-threaded. If the time arrives when your function is supposed to execute (based on how you called setTimer), and the parent code is still running, the function will not execute until the parent code has completed.


There is only a single thread; see: Node.js on multi-core machines

I would speculate that this is because Multiple threads are not supported in the underlying V8 JavaScript engine since typically JavaScript executes within a browser (where in a windows case there is only a single UI thread) and does not support multiple threads.


There's is this thing in javascript called Run-to-Completion which ensures that if a code is executing it executes completely before any other (asynchronous) code runs, hence, no concurrency issues.

In case of your example whenever the timer callback is called it will execute completely and will never be pre-empted in middle to execute some other code.

See Why no concurrency control tool in javascript for more details.

0

精彩评论

暂无评论...
验证码 换一张
取 消