Hacker News new | ask | show | jobs
by stepstep 4218 days ago
Really? I've never seen any synchronization code (e.g., locks) in JavaScript. If multiple threads can execute async tasks in parallel, doesn't that mean JavaScript needs synchronization primitives? Most JS code I've seen in the wild relies implicitly on the single-threaded assumption—that only one callback (for example) will run at a time.
2 comments

Say you wanna make an HTTP request.

What node will do is kick off the process (dns, grab a socket, connect tcp, write the header, wait for response etc.)... but it won't wait for any of this to finish, it just starts it on another thread. That thread doesn't need any JS-level synchronization because it has nothing to do with JS. Furthermore, you can kick off multiple requests like this in parallel.

When a request is done and has data to pass back, the external thread will queue up a V8 event. When V8 is free and is ready for the next event, it will see the finished request and trigger your callback with the data. When you're done handling that data (in Javascipt), V8 will wait for the next event and so on.

So you see, it's parallel but doesn't need any JS synchronizatioon.

> the external thread will queue up a V8 event

> So you see, it's parallel but doesn't need any JS synchronizatioon.

I don't know much about V8/Node internals, but I think we can regard the queue as a synchronization primitive? Granted, from what you say it's not in JS, but it's there, so at least some JS implementations need synchronization.

This is not done in parallel. Only one block of javascript is being executed at any given time. There is also no concept of preemption, if your function runs forever no other other events or callbacks will be handled.
How much time in a typical Node application is spent executing JS, vs. how much is in the C++ networking code?
JavaScript does not share memory between threads. No shared memory - no need for sync code. Instead it uses message passing and event loop to do the sync for you.

The way it's implemented is similar to Windows 3.x times - collaborative multitasking. Then there is no code to execute in your thread, an background event loop runs, listens for messages from another threads and calls appropriate callback function in your thread.

This design has the benefit of being simple to do simple stuff. And near impossible for more complex multithreaded algorithms that require shared memory.