This is the 16th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

preface

Front-end developers often say, “JavaScript is single-threaded.” This phrase, while somewhat simplistic, describes the general behavior of JavaScript in the browser. As such, it is very useful as a teaching tool to help Web developers understand JavaScript. Single threading means that you cannot delegate work to separate threads or processes, as multithreaded languages do. The single threading of JavaScript ensures that it is compatible with different browser apis. If JavaScript can execute concurrent changes in multiple threads, then an API like DOM will have a problem. Therefore, traditional concurrency structures such as POSIX threads or Java’s Thread class are not appropriate for JavaScript. This is where worker threads are valuable: they allow the work of the main thread to be transferred to separate entities without changing the existing single-threaded model. Although the various worker threads covered in this chapter come in different forms and functions, the common feature is that they are independent of the main JavaScript execution environment.

Introduction to Worker Threads

A JavaScript environment is actually a virtual environment running within a managed operating system. Each page opened in the browser is assigned its own environment. This way, each page has its own memory, event loop, DOM, and so on. Each page acts as a sandbox without interfering with other pages. For a browser, managing multiple environments at the same time is very simple, because all of these environments execute in parallel. With worker threads, the browser can assign a completely separate secondary subenvironment to the original page environment. This subenvironment cannot interoperate with apis (such as DOM) that rely on single-threaded interaction, but can execute code in parallel with the parent environment.

Worker threads and threads

It is often necessary to compare worker threads to execution threads. In many ways, this is an apt comparison, because worker threads and threads do have a lot in common.

  • Worker threads are implemented in terms of actual threads. For example, the Blink browser engine implements workerThreads for worker threads

Corresponds to the underlying thread.

  • Worker threads execute in parallel. While both the page and worker threads are single-threaded JavaScript environments, the instructions in each environment are

It can be executed in parallel.

Worker threads can share some memory. Worker threads can use the SharedArrayBuffer to share content across multiple environments. While threads use locks for concurrency control, JavaScript uses the Atomics interface for concurrency control. Worker threads are similar to threads in many ways, but there are also important differences.

  • Worker threads do not share all memory. In the traditional threading model, multiple threads have the ability to read and write to a shared memory space. In addition to the SharedArrayBuffer, data coming in and out of the worker thread needs to be copied or transferred.
  • Worker threads are not necessarily in the same process. Typically, a process can generate multiple threads within it. According to the browser

Worker threads may or may not belong to the same process as the page. For example, Chrome’s Blink engine uses separate processes for shared worker threads and service worker threads.

  • Creating worker threads is more expensive. The worker thread has its own separate event loop, global object, event handler, and

Other features required for JavaScript environments. The costs of creating these structures cannot be ignored

Worker threads are not intended to replace threads in either form or function. The HTML Web Worker threading specification says something like this:

Worker threads are relatively heavy and are not recommended to be used in large numbers. For example, for a 4 megapixel image, it is not appropriate to start a worker thread for each pixel. Typically, worker threads should be long-running, have high startup costs, and have a high memory footprint per instance.

The type of worker thread

The Web worker threads specification defines three main types of worker threads: dedicated worker threads, shared worker threads, and worker author threads. Modern browsers support these worker threads.

  • 1. Dedicated worker threads

Dedicated Worker threads, often referred to simply as Worker threads, Web workers, or workers, are a practical tool that allows scripts to create a separate JavaScript thread to perform delegated tasks. A dedicated worker thread, as its name implies, can only be used by the page on which it was created.

  • 2. Share worker threads

Shared worker threads are very similar to dedicated worker threads. The main difference is that shared worker threads can be used in multiple different contexts, including different pages. Any script that is the same as the script that created the shared worker thread can send messages to or receive messages from the shared worker thread.

  • 3. The service worker thread

Service worker threads are distinct from dedicated worker threads and shared worker threads. Its primary purpose is to intercept, redirect, and modify requests from the page, acting as an arbiter of network requests.

WorkerGlobalScope

On a Web page, the Window object can expose various global variables to scripts running in it. Inside worker threads, there is no concept of Windows. The global object here is an instance of WorkerGlobalScope, exposed by the self keyword.

WorkerGlobalScope property and method

Navigator: returns the WorkerNavigator associated with the worker thread.

  • Self: Returns the WorkerGlobalScope object.
  • Location: Returns the WorkerLocation associated with the worker thread.
  • Performance: Returns a performance object containing only specific properties and methods.
  • Console: Returns the console object associated with the worker thread; There are no restrictions on the API.
  • Caches: Returns the CacheStorage object associated with the worker thread; There are no restrictions on the API.
  • IndexedDB: Returns an IDBFactory object.
  • IsSecureContext: Returns a Boolean value indicating whether the worker thread context is safe.
  • Origin: Returns the source of the WorkerGlobalScope.

Similarly, some of the methods exposed on the self object are subsets of the methods on the window. These methods on self operate just like their counterparts on window.

  • atob()
  • btoa()
  • clearInterval()
  • clearTimeout()
  • createImageBitmap()
  • fetch()
  • setInterval()
  • setTimeout()

WorkerGlobalScope also adds a new global method, importScripts(), available only within worker threads. This method is described later in this chapter.

A subclass of WorkerGlobalScope

WorkerGlobalScope is not implemented everywhere. Each type of worker thread uses its own specific global object, which is inherited from WorkerGlobalScope.

  • Use DedicatedWorkerGlobalScope dedicated worker threads.
  • Shared worker threads use SharedWorkerGlobalScope.
  • The service worker thread uses ServiceWorkerGlobalScope.

That’s all for this post, thank you very much for reading here, if this article is good or a little bit of help to you, please like, follow, share, of course, any questions can be discussed in the comments, I will actively answer, thanks again 😁