Thread
Thread()函数用于创建并发线程。
Thread(func, ...args)
Thread(...items)示例
-
同时创建一个自定义函数和一个匿名函数的并发线程。
javascriptfunction test1(a, b, c) { Log("test1:", a, b, c) } function main() { var t1 = threading.Thread(test1, 1, 2, 3) var t2 = threading.Thread(function (msg) { Log("msg:", msg) }, "Hello thread2") t1.join() t2.join() } -
使用
Thread(...items)形式创建并发线程,按顺序执行多个函数。javascriptfunction test1(msg) { Log("msg:", msg) test2("Hello test2") } function main() { var t1 = threading.Thread( [function(a, b, c) {Log(a, b, c)}, 1, 2, 3], [test1, "Hello test1"], [`function test2(msg) {Log("msg:", msg)}`]) t1.join() } -
支持向并发执行函数的参数中传入函数。
javascriptfunction testFunc1(p) { Log("testFunc1 p:", p) } function main() { threading.Thread(function(pfn) { var threadName = threading.currentThread().name() var threadId = threading.currentThread().id() pfn(`in thread threadName: ${threadName}, threadId: ${threadId}`) }, testFunc1).join() } -
支持传入函数字符串,可动态导入外部库进行并发计算。
javascriptfunction ml(input) { const net = new brain.NeuralNetwork() net.train([ { input: [0, 0], output: [0] }, { input: [0, 1], output: [1] }, { input: [1, 0], output: [1] }, { input: [1, 1], output: [0] }, ]) return net.run(input) } function main() { var ret = threading.Thread([ml, [1, 0]], [HttpQuery("https://unpkg.com/brain.js")]).join() // ret: {"id":1,"terminated":false,"elapsed":337636000,"ret":{"0":0.9339330196380615}} Log(ret) }
返回值
| 类型 | 描述 |
|
|
参数
| 名称 | 类型 | 必填 | 描述 |
func | function | 是 | 参数 |
arg | string / number / bool / object / array / function / any (系统支持的所有类型) | 否 | 参数 |
item | array | 是 | 参数 |
参考
备注
传入Thread()函数用于并发执行的线程函数func运行在隔离环境中,因此无法直接引用线程外部的变量,引用时会导致编译失败。同时,线程内不支持引用其他闭包函数。线程内部可以调用平台提供的所有API,但不能调用用户自定义的其他函数。
当线程执行完毕且没有被持续引用时,系统底层会自动回收线程相关的资源,无需显式调用join()函数来释放资源。如果存在持续引用导致无法释放资源,当并发数量超过2000个时会报错:InternalError: too many routine wait, max is 2000。
支持回测系统、实盘环境。所有并发线程相关的函数在回测系统中仅作为代码兼容性支持,实际不会真正执行并发线程,本章不再赘述。