| scriptURL | string | Yes | URL of the script to be executed by the worker thread.<br>In the FA or stage model, DevEco Studio creates a **Worker** project in either of the following scenarios:<br>(a) The **workers** directory is at the same level as the **pages** directory.<br>(b) The **workers** directory is at a different level from the **pages** directory.
| scriptURL | string | Yes | Directory of the script to be executed by the **Worker** instance.<br>In the FA or stage model, DevEco Studio creates a **Worker** project in either of the following scenarios:<br>(a) The script directory is at the same level as the **pages** directory.<br>(b) The script directory is at a different level from the **pages** directory.
| options | [WorkerOptions](#workeroptions) | No | Options that can be set for the **Worker** instance. |
**Return value**
...
...
@@ -65,25 +63,26 @@ A constructor used to create a **Worker** instance.
```js
importworkerfrom'@ohos.worker';
// Create a worker thread.
// Create a Worker instance.
// In the FA model, the workers and pages directories are at the same level.
// scriptURL—— Description of "entry/ets/workers/worker.ts".
// For the script URL "entry/ets/workers/worker.ts" in the stage model:
// entry is the value of the name attribute under module in the module.json5 file.
// ets indicates the programming language in use.
```
Depending on whether the works and pages directories are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file.
Depending on whether the worker script directory and **pages** directory are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file.
(1) The worker script directory and **pages** directory are at the same level.
(1) If the workers and pages directories are at the same level, the configuration is optional.
In the FA model:
```json
...
...
@@ -105,7 +104,8 @@ In the stage model:
}
}
```
(2) If the workers and pages directories are at different levels, the configuration is mandatory.
(2) The worker script directory and **pages** directory are at different levels.
Sends a message to the worker thread. The message data is transferred using the structured clone algorithm.
Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information).
Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **DedicatedWorkerGlobalScope** class inherits from [WorkerGlobalScope](#workerglobalscope).
Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. This class inherits from [WorkerGlobalScope](#workerglobalscope).
Defines the event handler to be called when the worker thread receives a message sent by the host thread through **worker.postMessage**. The event handler is executed in the worker thread.
Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread.
| All primitive types | The Symbol type is not included. | Yes |
| Date | | Yes |
| String | | Yes |
| RegExp | | Yes |
| Array | | Yes |
| Map | | Yes |
| Set | | Yes |
| Object | Only plain objects are supported. Objects with functions are not supported. | Yes |
| ArrayBuffer | The transfer capability is provided. | Yes |
| TypedArray | | Yes |
Exception: When an object created through a custom class is passed, no serialization error occurs. However, the attributes (such as Function) of the custom class cannot be passed through serialization.
workerInstance.postMessage("message from main to worker");
workerInstance.onmessage=function(d){
// When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method.
letdata=d.data;
}
```
```js
// worker.js
importworkerfrom'@ohos.worker';
constparentPort=worker.parentPort;
classMyModel{
Init(){
this.name="wzy"
this.age=18
}
SetName(){
this.name="WZY"
}
}
parentPort.onmessage=function(d){
console.log("worker.js onmessage");
letdata=d.data;
letfunc1=function(){
console.log("post message is function");
}
letobj1={
"index":2,
"name1":"zhangshan",
setName(){
this.index=3;
}
}
letobj2=newMyModel();
// parentPort.postMessage(func1); A serialization error occurs when passing func1.
// parentPort.postMessage(obj1); A serialization error occurs when passing obj1.
parentPort.postMessage(obj2);// No serialization error occurs when passing obj2.
}
parentPort.onmessageerror=function(e){
console.log("worker.js onmessageerror");
}
parentPort.onerror=function(e){
console.log("worker.js onerror");
}
```
### Memory Model
The worker thread is implemented based on the actor model. In the worker interaction process, the JS main thread can create multiple worker threads, each of which are isolated and transfer data through sequentialization. They complete computing tasks and return the result to the main thread.
Each actor concurrently processes tasks of the main thread. For each actor, there is a message queue and a single-thread execution module. The message queue receives requests from the main thread and other actors; the single-thread execution module serially processes requests, sends requests to other actors, and creates new actors. These isolated actors use the asynchronous mode and can run concurrently.
### Precautions
- Currently, a maximum of seven workers can co-exist.
- If the number of workers exceeds the upper limit, the error message "Too many workers, the number of workers exceeds the maximum." is displayed.
- To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance.
- Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them.
## Sample Code
### FA Model
```js
// main.js (The following assumes that the workers and pages directories are at the same level.)
// main.js (The following assumes that the worker script directory and pages directory are at the same level.)