输入/搜索内容
内置函数
Global
Log
Market
Trade
Account
Futures
Threads
threading
threading.Thread
threading.getThread
threading.mainThread
threading.currentThread
threading.Lock
threading.Condition
threading.Event
threading.Dict
threading.Serve
threading.pending
Thread
ThreadLock
ThreadEvent
ThreadCondition
ThreadDict
Server
TA
Talib
OS
结构体
内置变量

创建并发线程。

Thread(func, ...args)
Thread(...items)

示例

  • 同时为一个自定义函数和一个匿名函数创建并发线程。

    javascript
    function 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)形式创建并发线程,并顺序执行多个函数。

    javascript
    function 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() }
  • 支持将函数作为参数传入并发执行函数。

    javascript
    function 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() }
  • 支持传入函数字符串,可动态导入外部库进行并发计算。

    javascript
    function 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) }

返回值

类型描述

Thread对象

Thread对象,用于管理所创建的并发线程、进行线程间通信等。

参数

名称类型必填描述

func

function

是

用于并发执行的函数(通过引用传递),支持传入匿名函数。func可接受多个参数,这些参数在并发执行时通过...args传入,因此func的参数列表需要与...args保持一致。

arg

string / number / bool / object / array / function / any

否

回调执行时传递给func(即并发线程执行函数)的实际参数。参数arg可以有多个,func的参数列表需要与...args保持一致。

item

array

是

一个数组,包含待并发执行的函数引用及其参数。调用Thread函数时,可以传入多组参数item。

参考

备注

传入Thread()函数用于并发执行的线程函数func运行在隔离环境中,因此无法直接引用线程外部的变量,否则会导致编译失败。同时,线程内不支持引用其他闭包函数。线程内部可以调用平台提供的所有API,但不能调用用户自定义的其他函数。

当线程执行完毕且未被持续引用时,系统底层会自动回收线程相关资源,无需显式调用join()函数来释放资源。如果因持续引用导致资源无法释放,当并发数量超过2000个时会报错:InternalError: too many routine wait, max is 2000。

支持回测系统和实盘环境。所有并发线程相关的函数在回测系统中仅用于代码兼容,实际不会真正并发执行线程,本章不再赘述。

线程函数中未捕获的异常会输出错误日志(thread #线程Id exit abnormally 异常信息)并停止整个策略:主线程随之中断,执行onerror()函数后以错误状态结束。线程内部可以使用try...catch自行处理异常,以避免策略停止。被terminate()终止的线程不视为异常。