search
HomeWeb Front-endJS TutorialResearch on Web worker multi-thread API in JavaScript_javascript skills

HTML5 supports APIs such as Web Worker, allowing web pages to execute multi-threaded code safely. However, Web Worker is actually subject to many limitations, because it cannot truly share memory data and can only make status notifications through messages, so it cannot even be called "multi-threading" in the true sense.

The interface of Web Worker is very inconvenient to use. It basically comes with a sandbox, runs an independent js file in the sandbox, and communicates with the main thread through postMessage and onMessage:

Copy code The code is as follows:

var worker = new Worker("my.js");
var bundle = {message:'Hello world', id:1};
worker.postMessage(bundle); //postMessage can pass a serializable object
worker.onmessage = function(evt){
Console.log(evt.data); //Compare the object passed back from the worker with the object in the main thread
console.log(bundle); //{message:'Hello world', id:1}
}

Copy code The code is as follows:

//in my.js
onmessage = function(evt){
var data = evt.data;
Data.id ;
PostMessage(data); //{message:'Hello world', id:2}
}

The results obtained can be found that the id of the data obtained in the thread has increased, but after it is passed back, the id in the bundle of the main thread has not changed. Therefore, the object passed in the thread is actually copied, so If so, the threads do not share data and avoid read and write conflicts, so it is safe. The price of ensuring thread safety is to limit the ability to manipulate main thread objects in the thread.

Such a limited multi-threading mechanism is very inconvenient to use. We certainly hope that Worker can support making the code look like it has the ability to operate multiple threads at the same time. For example, support code that looks like the following:

Copy code The code is as follows:

var worker = new ThreadWorker(bundle /*shared obj*/);

worker.run(function(bundle){
//do sth in worker thread...
This.runOnUiThread(function(bundle /*shared obj*/){
                  //do sth in main ui thread...
});
//...
});

In this code, after we start a worker, we can let any code run in the worker, and when we need to operate the ui thread (such as reading and writing DOM), we can return to the main thread for execution through this.runOnUiThread.

So how to implement this mechanism? Look at the code below:

Copy code The code is as follows:

function WorkerThread(sharedObj){
This._worker = new Worker("thread.js");
This._completes = {};
This._task_id = 0;
This.sharedObj = sharedObj;

var self = this;
This._worker.onmessage = function(evt){
      var ret = evt.data;
If(ret.__UI_TASK__){
                    //run on ui task
          var fn = (new Function("return " ret.__UI_TASK__))();
                 fn(ret.sharedObj);
         }else{
                self.sharedObj = ret.sharedObj;
                self._completes[ret.taskId](ret);
}
}
}

WorkerThread.prototype.run = function(task, complete){
var _task = {__THREAD_TASK__:task.toString(), sharedObj: this.sharedObj, taskId: this._task_id};
This._completes[this._task_id ] = complete;
This._worker.postMessage(_task);
}

The above code defines a ThreadWorker object, which creates a Web Worker that runs thread.js, saves the shared object SharedObj, and processes the messages sent back by thread.js.

If a UI_TASK message is returned from thread.js, then run the function passed by the message, otherwise execute the complete callback of run. Let’s take a look at how thread.js is written:

Copy code The code is as follows:

onmessage = function(evt){
var data = evt.data;

if(data && data.__THREAD_TASK__){
        var task = data.__THREAD_TASK__;
         try{
               var fn = (new Function("return " task))();

var ctx = {
threadSignal: true,
sleep: function(interval){
                       ctx.threadSignal = false;
                          setTimeout(_run, interval);
                 },
                  runOnUiThread: function(task){
PostMessage({__UI_TASK__:task.toString(), sharedObj:data.sharedObj});
                }
            }

function _run(){
                  ctx.threadSignal = true;
              var ret = fn.call(ctx, data.sharedObj);
PostMessage({error:null, returnValue:ret, __THREAD_TASK__:task, sharedObj:data.sharedObj, taskId: data.taskId});
            }

_run(0);

}catch(ex){
PostMessage({error:ex.toString(), returnValue:null, sharedObj: data.sharedObj});
}
}
}

As you can see, thread.js receives messages from the ui thread, the most important of which is THREAD_TASK, which is the "task" passed by the ui thread that needs to be executed by the worker thread. Since the function is not serializable, What is passed is a string. The worker thread parses the string into a function to execute the task submitted by the main thread (note that the shared object sharedObj is passed in in the task). After the execution is completed, the return result is passed to the ui thread through the message. Let's take a closer look. In addition to the return value returnValue, the shared object sharedObj will also be passed back. When passing back, since the worker thread and the ui thread do not share objects, we artificially synchronize the objects on both sides through assignment (is this thread safe? ? Why? )

You can see that the whole process is not complicated. After this implementation, this ThreadWorker can be used in the following two ways:

Copy code The code is as follows:

var t1 = new WorkerThread({i: 100} /*shared obj*/);

        setInterval(function(){
            t1.run(function(sharedObj){
                    return sharedObj.i ;
                },
                function(r){
                    console.log("t1>" r.returnValue ":" r.error);
                }
            );
        }, 500);
var t2 = new WorkerThread({i: 50});

        t2.run(function(sharedObj){  
            while(this.threadSignal){
                sharedObj.i ;

                this.runOnUiThread(function(sharedObj){
                    W("body ul").appendChild("

  • " sharedObj.i "
  • ");
                    });

                    this.sleep(500);
                }
                return sharedObj.i;
            }, function(r){
                console.log("t2>" r.returnValue ":" r.error);
            });

    这样的用法从形式和语义上来说都让代码具有良好的结构,灵活性和可维护性。

    好了,关于Web Worker的用法探讨就介绍到这里,有兴趣的同学可以去看一下这个项目:https://github.com/akira-cn/WorkerThread.js (由于Worker需要用服务器测试,我特意在项目中放了一个山寨的httpd.js,是个非常简陋的http服务的js,直接用node就可以跑起来)。

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

    Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

    Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

    Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

    Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

    The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

    The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

    JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

    Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

    JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

    The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

    The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

    Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

    Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

    Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

    Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!