简体   繁体   中英

To multithread or not to multithread - JavaScript

I am currently experimenting with a JavaScript shooting game similar to space invaders. The way it is coded now, either the projectile with move or the ship. Anyone that has played the original will know that this isn't good. I remember going over multithreading in my Java class and was wondering if this was the right way to go or is there another way to do it? For instance:

Thread Move start;
Thread Move run;
Thread Shoot start;
Thread Move run;
Thread Shoot run;
Thread Shoot end;
Thread Move run;
Thread Move end;

You can use WebWorkers in Javascript, but they act nowhere near the same as a true multithreaded environment, as in java. You will have to take a different approach to your game development, using a sort of round robin technique to update the logic of your game all under the same thread, sorry. :( The support added for threading in javascript is still very hoaky, and almost a gimmick in my opinion, the only one who is kind of there is Chrome, because you do not necessarily copy all data passed to the thread. Here is why threads in javascript are hamstrung:

  1. No true access to the dom
  2. Most if not all (depending on engine) data must be copied to other thread, meaning that if you want to process a huge amount of data in the background, you will have to perform a copy on that data first
  3. Errors on WebWorkers are not yet always completely obvious (Sometimes you get random, hard to understand errors)

With that WebWorkers have great potential, but for me, their use is severely limited by the limitations placed on them at this time. Maybe you can find a clever use for them in your game.

Traditionally, JavaScript was single-threaded, so using threads like you are used to in Java was not feasible. A relatively recent addition to JavaScript is web workers ( spec here ) which provides true multi-threading. However, support among browsers is somewhat variable, you are restricted on what can be done by a worker thread, and communication between threads is painful.

You can also use something like Clumpy.js to simulate asynchronous execution.

Whatever you do, it's important to not block the main thread. The entire browser window becomes unresponsive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM