DEV Community

loading...

Discussion on: Prove that JavaScript runs in a single thread

Collapse
curtisfenner profile image
Curtis Fenner • Edited

This doesn't strictly prove that JavaScript is only run on a single thread, because concurrency is very subtle.

In C++, this example (using, e.g., std::thread to start a second thread) might hang because there's no explicit synchronization of the loop variable, even though C++ can run on multiple threads

In Go, this example (using go to start a goroutines) might hang because the thread scheduler isn't fair, and might never preempt the loop without a wait in it.

Busy waiting is a bad idea in any language -- and it's why you should basically never notice that JavaScript is single threaded. The only way it should really affect your code is that you don't need mutexes/locks to protect 'critical sections' where you need to make many updates at once to be consistent

Collapse
rajajaganathan profile image
Raja Jaganathan Author • Edited

Agreed!, it also confirms that both event loop and main thread running on a same thread.