


Research 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:
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}
}
//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:
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:
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:
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:
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("
});
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就可以跑起来)。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Function exception handling in C++ is particularly important for multi-threaded environments to ensure thread safety and data integrity. The try-catch statement allows you to catch and handle specific types of exceptions when they occur to prevent program crashes or data corruption.

PHP multithreading refers to running multiple tasks simultaneously in one process, which is achieved by creating independently running threads. You can use the Pthreads extension in PHP to simulate multi-threading behavior. After installation, you can use the Thread class to create and start threads. For example, when processing a large amount of data, the data can be divided into multiple blocks and a corresponding number of threads can be created for simultaneous processing to improve efficiency.

There are two common approaches when using JUnit in a multi-threaded environment: single-threaded testing and multi-threaded testing. Single-threaded tests run on the main thread to avoid concurrency issues, while multi-threaded tests run on worker threads and require a synchronized testing approach to ensure shared resources are not disturbed. Common use cases include testing multi-thread-safe methods, such as using ConcurrentHashMap to store key-value pairs, and concurrent threads to operate on the key-value pairs and verify their correctness, reflecting the application of JUnit in a multi-threaded environment.

Concurrency and multithreading techniques using Java functions can improve application performance, including the following steps: Understand concurrency and multithreading concepts. Leverage Java's concurrency and multi-threading libraries such as ExecutorService and Callable. Practice cases such as multi-threaded matrix multiplication to greatly shorten execution time. Enjoy the advantages of increased application response speed and optimized processing efficiency brought by concurrency and multi-threading.

Mutexes are used in C++ to handle multi-threaded shared resources: create mutexes through std::mutex. Use mtx.lock() to obtain a mutex and provide exclusive access to shared resources. Use mtx.unlock() to release the mutex.

In a multi-threaded environment, C++ memory management faces the following challenges: data races, deadlocks, and memory leaks. Countermeasures include: 1. Use synchronization mechanisms, such as mutexes and atomic variables; 2. Use lock-free data structures; 3. Use smart pointers; 4. (Optional) implement garbage collection.

Multi-threaded program testing faces challenges such as non-repeatability, concurrency errors, deadlocks, and lack of visibility. Strategies include: Unit testing: Write unit tests for each thread to verify thread behavior. Multi-threaded simulation: Use a simulation framework to test your program with control over thread scheduling. Data race detection: Use tools to find potential data races, such as valgrind. Debugging: Use a debugger (such as gdb) to examine the runtime program status and find the source of the data race.

In multithreaded C++, exception handling follows the following principles: timeliness, thread safety, and clarity. In practice, you can ensure thread safety of exception handling code by using mutex or atomic variables. Additionally, consider reentrancy, performance, and testing of your exception handling code to ensure it runs safely and efficiently in a multi-threaded environment.
