Kuldeep Yadav
Kuldeep Yadav

Reputation: 1806

Javascript: How multiple threads are implemented in javascript?

I am building a small two-player gaming app. It is very important to send data from one player to another in real-time and for that sockets look promising.

A few places I read that javascript doesn't support multithreading. Then what can be possible solution for both side communication as two threads will be needed to manage C1->C2 and C2->C1 communication in parallel.

My high-level architecture looks like

enter image description here

How can three threads can be managed by javascript in a webpage? One for C1 to C2 message transfer, second for C2 to C1 message transfer and third for user interface?

Upvotes: 0

Views: 358

Answers (1)

Ben Aston
Ben Aston

Reputation: 55729

A JavaScript program runs on a single thread of execution using a "run to completion" semantic.

Operations that would normally block in other languages are non-blocking, and simply handed off to the host (in this case, the browser), with your program notified of progress asynchronously via events.

When the host raises an event to be consumed by your program (eg. an inbound message), it puts a notification of that event in a queue as a "job". When that job reaches the front of the queue, and as soon as the call stack is empty (ie. the current script being run has run to completion), the JavaScript runtime dequeues the job and invokes the continuation function associated with it (ie. the part of your program configured to handle the event).

Your game will be sending messages over the network (eg via WebSocket). Your program will simply hand each message to the browser. This process is not computationally expensive or time consuming. The browser is multithreaded and will handle the low-level and time consuming networking concerns for you.

JavaScript is an event-based language. If you wish to be notified of future events related to a message you sent, then you can supply a callback (or use a promise) to be invoked by the runtime in the future at the appropriate time, rather than simply waiting for it. In this way the time available on the main thread of execution is used efficiently.

Your game loop will probably use requestAnimationFrame. That gives you about 16 milliseconds of computation per frame. Computation of game state might take a few milliseconds. Handling scheduled and time-based events might take another few milliseconds. Finally rendering needs some time too. In effect your program cooperatively multi-tasks on a single thread of execution.

For long-running, computationally expensive tasks you can use the Worker API to create new threads of execution with which you can communicate in a controlled way, but you will probably not need this here.

There is plenty of information online already about this topic. Search for "how the event loop works".

Relevant questions here, here, here, here, and here.

Upvotes: 2

Related Questions