1.0.4 • Published 11 months ago

@kuiu/task-worker v1.0.4

Weekly downloads
-
License
MIT
Repository
-
Last release
11 months ago

TaskWorker(任务调度器)

TaskWorker makes WebWorkers enjoyable. TaskWorker is a tiny library (1.1kB), that removes the mental barrier of thinking about postMessage and hides the fact that you are working with workers.

At a more abstract level it is an RPC implementation for postMessage and ES6 Proxies.

$ npm install --save @kuiu/task-worker

Introduction

On mobile phones, and especially on low-end mobile phones, it is important to keep the main thread as idle as possible so it can respond to user interactions quickly and provide a jank-free experience. The UI thread ought to be for UI work only. WebWorkers are a web API that allow you to run code in a separate thread. To communicate with another thread, WebWorkers offer the postMessage API. You can send JavaScript objects as messages using myWorker.postMessage(someObject), triggering a message event inside the worker.

TaskWorker turns this messaged-based API into a something more developer-friendly by providing an RPC implementation: Values from one thread can be used within the other thread (and vice versa) just like local values.

任务调度器

  • 负责将耗时任务拆分到多个线程中执行
  • 基于任务调度的方式使用多线程运行任务
  • A 主线程负责通信,调度和消费消息
  • B 线程 负责执行实体
  • C 线程 负责执行实体
  • B C 线程执行实体不重复

main.js

import * as TaskWorker from "@kuiu/task-worker";
async function init() {
  // WebWorkers use `postMessage` and therefore work with TaskWorker.
  const obj = TaskWorker.createTaskPorxy([new Worker("worker.js"), new Worker("worker.js")], [], null, true);
  alert(`Counter: ${await obj.counter}`);
  await obj.inc();
  alert(`Counter: ${await obj.counter}`);
}
init();

worker.js

const obj = {
  counter: 0,
  inc() {
    this.counter++;
  },
};

const Worker = new TaskWorker.TaskWorker(self)
Worker.expose('default', obj);

main.js

function callback(value) {
  alert(`Result: ${value}`);
}
async function init() {
  const remoteFunction = TaskWorker.createTaskPorxy([new Worker("worker.js")], [], null, true);
  await remoteFunction(TaskWorker.proxy(callback));
}
init();

worker.js

async function remoteFunction(cb) {
  await cb("A string from a worker");
}
const Worker = new TaskWorker.TaskWorker(self)
Worker.expose('default', remoteFunction);
1.0.4

11 months ago

1.0.3

12 months ago

1.0.2

12 months ago

1.0.1

1 year ago

1.0.0

1 year ago