输入/搜索内容
内置函数
Global
Log
Market
Trade
Account
Futures
Exchange
IO
Network
Storage
Threads
exchange.Go
EventLoop
ctx.subscribe
ctx.poll
ctx.order
ctx.cancel
ctx.submit
Subscription
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) 形式创建并发线程,在一个线程里执行多组函数:先执行最后一组(源码字符串,定义 test2),再执行第二组(test1 调用 test2),最后执行第一组。

    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,"error":null,"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可以传入多组。多组时在同一个线程里按以下顺序执行:先从最后一组倒序执行到第二组,最后执行第一组;第一组是主函数,其返回值作为join()结果中的ret。后面几组通常用来定义函数、加载库:源码字符串按全局脚本执行,其中定义的函数可以在主函数中调用(源码字符串不接收参数)。

参考

备注

传入Thread()函数用于并发执行的线程函数func运行在隔离环境中,因此无法直接引用线程外部的变量,引用时调用Thread()会报错:external variables reference are not allowed。同时,线程内不支持引用其他闭包函数。线程内部可以调用平台提供的所有API,但不能直接调用用户自定义的其他函数;需要用到的函数可以作为参数传入,或者用Thread(...items)形式在后面几组中定义。

当线程执行完毕且没有被持续引用时,系统底层会自动回收线程相关的资源,无需显式调用join()函数来释放资源。

支持回测系统、实盘环境;所有并发线程相关的函数在回测系统中仅作为代码兼容性支持,实际不会真正执行并发线程。