# Multithreading Worker

For games, 16ms per frame is extremely valuable. If there are some tasks that can be processed asynchronously, they can be placed in Worker to run. After the end of the run, the results are returned to the main thread. Worker runs in a separate global context and thread, and cannot call the method of main thread directly. Worker also does not have the ability to render. For the data transmission between the Worker and the main thread, the two sides use Worker.postMessage() to send the data, and Worker.onMessage() to receive the data. The transmitted data is not directly shared but is copied.

# Steps

# 1. Configure Worker Information

The directory where the Worker code is to be placed can be configured in game.json and the code in the directory will be packaged into a file:

Configuration Example:

{
  "workers": "workers"
}
# 2. Add Worker Code File

According to the configuration in step 1, create the following two entry files in the code directory:

workers/request/index.js
workers/request/utils.js
workers/response/index.js

After adding, the structure of the directory is as follows:

├── game.js
├── game.json
├── project.config.json
└── workers
    ├── request
    │   ├── index.js
    │   └── utils.js
    └── response
        └── index.js

# 3. Write Worker code

Writing Worker response code in workers/request/index.js

var utils = require('./utils')

// Executing context in Worker thread will expose a `worker` object globally, and worker.onMessage/postMessage can be called directly.
worker.onMessage(function (res) {
  console.log(res)
})

# 4. Initialize Worker in the Main Thread

Initialize Worker in the main thread's code game.js

Var worker = wx.createWorker(’workers/request/index.js’) // Filename specifies the entry file path of worker, which is an absolute path

# 5. The Main Thread Sends a Message to the Worker

worker.postMessage({
  msg: 'hello worker'
})

See the worker interface specification for other interfaces of the worker object.

# Tips

  1. The maximum number of concurrent Workers is limited to one. Please end the current Worker with Worker.terminate() before creating the next one.
  2. The code in the Worker can only require files in the specified Worker path, and cannot reference other paths
  3. The Worker's entry file is specified by wx.createWorker(), and the developer can dynamically specify the Worker entry file.
  4. The wx family API is not supported in Worker
  5. Message sending is not supported between Workers
点击咨询小助手