Skip to content

线程模块(thread / sharedState)

子线程脚本文件名须以 _thread.js 结尾;线程内无法访问主线程闭包变量,请用 sharedState 通信。VS Code 推送主脚本时会自动附带同目录下全部 .js(含 *_thread.js)。

thread.run - 启动子线程

typescript
function thread.run(threadJsFileName: string): ThreadHandle;

参数说明:

参数名类型是否必填默认值描述
threadJsFileNamestring-相对脚本工程目录的文件名,须以 _thread.js 结尾,如 worker_thread.js

返回值:

类型描述
ThreadHandle线程控制对象(同步返回;字段 / 方法见下表)

返回字段:

字段名类型是否必填默认值描述
namestring-线程名称,一般为传入的脚本文件名
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;
}

返回字段:

字段名类型是否必填默认值描述
namestring-线程名称(脚本文件名)
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();

参数说明:

参数名类型是否必填默认值描述
keystring-set / get 的键名
valueunknown-set 写入的任意可序列化值
block() => void-withBatch 回调;宿主内原子执行多次 set

返回值:

方法类型描述
setvoid无返回
getunknown键对应的值;不存在时为 undefined(无固定对象字段)
withBatchvoid无返回
clearvoid清空全部键
javascript
sharedState.set('count', 0);
const n = sharedState.get('count');
sharedState.withBatch(() => {
 sharedState.set('a', 1);
 sharedState.set('b', 2);
});
sharedState.clear();