Appearance
线程模块(thread / sharedState)
子线程脚本文件名须以 _thread.js 结尾;线程内无法访问主线程闭包变量,请用 sharedState 通信。VS Code 推送主脚本时会自动附带同目录下全部 .js(含 *_thread.js)。
thread.run - 启动子线程
typescript
function thread.run(threadJsFileName: string): ThreadHandle;参数说明:
| 参数名 | 类型 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|---|
| threadJsFileName | string | 是 | - | 相对脚本工程目录的文件名,须以 _thread.js 结尾,如 worker_thread.js |
返回值:
| 类型 | 描述 |
|---|---|
| ThreadHandle | 线程控制对象(同步返回;字段 / 方法见下表) |
返回字段:
| 字段名 | 类型 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|---|
| name | string | 是 | - | 线程名称,一般为传入的脚本文件名 |
| cancel | () => boolean | 是 | - | 取消该线程;本地标记并通知宿主,返回 true |
| isCancelled | () => boolean | 是 | - | 是否已取消 |
| isExecuting | () => boolean | 是 | - | 是否仍在执行 |
javascript
sharedState.set('isRunning', true);
const t = thread.run('worker_thread.js');
while (t.isExecuting()) {
logi('进度', sharedState.get('progress'));
auto.sleep(500);
}
sharedState.set('isRunning', false);thread.stopAll - 停止全部子线程
typescript
function thread.stopAll(): boolean;参数说明:
| 参数名 | 类型 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|---|
| (无) | - | - | - | 无参数 |
返回值:
| 类型 | 描述 |
|---|---|
| boolean | 是否成功发出停止(同步) |
javascript
thread.stopAll();ThreadHandle - cancel / isCancelled / isExecuting
typescript
interface ThreadHandle {
name: string;
cancel(): boolean;
isCancelled(): boolean;
isExecuting(): boolean;
}返回字段:
| 字段名 | 类型 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|---|
| name | string | 是 | - | 线程名称(脚本文件名) |
| cancel() | boolean | — | - | 请求取消;返回是否接受取消 |
| isCancelled() | boolean | — | - | true 表示已取消 |
| isExecuting() | boolean | — | - | true 表示仍在执行 |
javascript
let t = thread.run('worker_thread.js');
t.cancel();
if (t.isCancelled()) logi('已取消');
if (t.isExecuting()) logi('运行中');sharedState - 跨线程共享
typescript
sharedState.set(key, value);
sharedState.get(key);
sharedState.withBatch(() => { ... });
sharedState.clear();参数说明:
| 参数名 | 类型 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|---|
| key | string | 是 | - | set / get 的键名 |
| value | unknown | 是 | - | set 写入的任意可序列化值 |
| block | () => void | 是 | - | withBatch 回调;宿主内原子执行多次 set |
返回值:
| 方法 | 类型 | 描述 |
|---|---|---|
| set | void | 无返回 |
| get | unknown | 键对应的值;不存在时为 undefined(无固定对象字段) |
| withBatch | void | 无返回 |
| clear | void | 清空全部键 |
javascript
sharedState.set('count', 0);
const n = sharedState.get('count');
sharedState.withBatch(() => {
sharedState.set('a', 1);
sharedState.set('b', 2);
});
sharedState.clear();