# Multi-threaded Worker

For a game, 16ms per frame is extremely important. If you have some tasks that can be processed asynchronously, you can run them in a Worker. After the task is run, the results are returned to the main thread. The [Worker]((Worker) runs in a separate global context and thread, and cannot directly call the methods of the main thread. In addition, the Worker does not possess rendering capabilities. Data is transfer between the Worker and the main thread using Worker.postMessage() to send data and Worker.onMessage() to receive data. The data to be transferred is not directly shared but copied.

# Process

# 1. Configure worker information

In game.json, you can configure a directory where Worker code is placed. The code in the directory is packaged into a file:

Configuration example:

{
  "workers": "workers"
}
# 2. Add worker code files

Based on the configuration in Step 1, create the following two entry files:

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

After the files are added, the directory structure is as follows:

├── game.js
├── game.json
├── project.config.json
└── workers
    ├── request
    │   ├── index.js
    │   └── utils.js
    └── response
        └── index.js
# 3. Write worker code

Write the worker response code in workers/request/index.js.

var utils = require('./utils')

// In the worker thread execution context, a `worker` object is globally exposed and can be directly called by worker.onMessage/postMessage.
worker.onMessage(function (res) {
  console.log(res)
})

# 4. Initialize Worker in the main thread

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

var worker = wx.createWorker('workers/request/index.js') // The filename specifies the worker entry file path as an absolute path.

# 5. The main thread sends a message to Worker

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

For other APIs related to worker objects, refer to Worker API Description.

# Tips

  1. The maximum concurrency of worker is one. Use Worker.terminate() to terminate the current worker before creating the next one.
  2. The code in the worker can only require files in the specified worker path. It cannot reference other paths.
  3. The worker entry files are specified when calling wx.createWorker(). Developers can dynamically specify the worker entry files.
  4. wx APIs are not supported in workers.
  5. Workers cannot send messages to each other.
点击咨询小助手