Hacker News new | past | comments | ask | show | jobs | submit login

Concurrency can be done on a singular thread



My understanding is that single-thread concurrency is essentially what Javascript does. It basically flickers between tasks very rapidly to simulate concurrency. Does that match your understanding or am I incorrect?


I don't think that "flickers between tasks very rapidly to simulate concurrency" is a good mental model for event loops. It's more like "runs one task at a time until it hits a suspension point," where a suspension point is something like an I/O operation. If you had an event loop that switched tasks between suspension points, then you'd still need locks for shared data.


It doesn’t simulate, and the “flicker” is named “event loop”, but otherwise you’ve got it right. The concurrency model is essentially cooperative, ie pending tasks wait for the current task on the event loop to unblock, and then they are each executed in turn (with several different scheduling priorities based on how they became pending, eg synchronous event callbacks, Promises, various timers).


> It basically flickers between tasks very rapidly to simulate concurrency.

That’s usually used a description of preemptive multitasking, like what you get running a modern OS on a single core (on multiple cores it’s also this but on each core). Every once in a small while, the current task is made to inhale chloroform, another task is chosen to wake and takes its place. Pro: you can’t hang any given task from a single thread; con: shared memory is very difficult to impossible, as you never know when you’ll be interrupted.

Browser JavaScript and UI interactions instead use cooperative multitasking, which you’ll also find in classic Mac OS, 16-bit Windows, basically every embedded system ever, and languages like Python and Lua. A task has to explicitly call out to the scheduler to hand off execution resources to the next one. Pro: as task switching only happens at clearly visible points, many of the horrors of shared memory are diminished; con: you can and will hang the UI (or other outside-world interactions) if you accidentally write an infinite loop or just do too much CPU-bound work without yielding (as any developer using one of the aforementioned systems knows).

For how this works in the browser environment specifically, see Jake Archbald’s superb talk[1].

[1] https://youtu.be/cCOL7MC4Pl0


You're mixing up concurrency with parallelism.





Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: