threading.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)形式创建并发线程,在一个线程里执行多组函数:先执行最后一组(源码字符串,定义 test2),再执行第二组(test1 调用 test2),最后执行第一组。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,"error":null,"ret":{"0":0.9339330196380615}} Log(ret) }
返回值
| 类型 | 描述 |
|
|
参数
| 名称 | 类型 | 必填 | 描述 |
func | function | 是 | 用于并发执行的函数(通过引用传递),支持传入匿名函数。 |
arg | string / number / bool / object / array / function / any | 否 | 在回调执行时传递给 |
item | array | 是 | 一个数组,第一个元素是函数引用或函数源码字符串,其余元素是该函数的参数;调用 |
参考
备注
传入Thread()函数用于并发执行的线程函数func运行在隔离环境中,因此无法直接引用线程外部的变量,引用时调用Thread()会报错:external variables reference are not allowed。同时,线程内不支持引用其他闭包函数。线程内部可以调用平台提供的所有API,但不能直接调用用户自定义的其他函数;需要用到的函数可以作为参数传入,或者用Thread(...items)形式在后面几组中定义。
当线程执行完毕且没有被持续引用时,系统底层会自动回收线程相关的资源,无需显式调用join()函数来释放资源。
支持回测系统、实盘环境;所有并发线程相关的函数在回测系统中仅作为代码兼容性支持,实际不会真正执行并发线程。