Threads
The FMZ Quant Trading Platform provides true multi-threading support for JavaScript language strategies at the system level, implementing the following objects:
| Object | Description | Notes |
|---|---|---|
| threading | Global multi-threading object | Member functions: Thread, getThread, mainThread, etc. |
| Thread | Thread object | Member functions: peekMessage, postMessage, join, etc. |
| ThreadLock | Thread lock object | Member functions: acquire, release. Can be passed as a parameter to thread execution functions into the thread environment. |
| ThreadEvent | Event object | Member functions: set, clear, wait, isSet. Can be passed as a parameter to thread execution functions into the thread environment. |
| ThreadCondition | Condition object | Member functions: notify, notifyAll, wait, acquire, release. Can be passed as a parameter to thread execution functions into the thread environment. |
| ThreadDict | Dictionary object | Member functions: get, set. Can be passed as a parameter to thread execution functions into the thread environment. |
threading
The threading object serves as a global multi-threading management tool, providing functions for creating concurrent threads, thread locks, condition variables, and more. This section introduces the member functions of the threading object. Only JavaScript language strategies support this object.
Thread
The Thread() function is used to create concurrent threads.
Thread(func, ...args)
Thread(...items)Examples
-
Create a concurrent thread with both a custom function and an anonymous function simultaneously.
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() } -
Use
Thread(...items)format to create concurrent threads that execute multiple functions sequentially.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() } -
Support passing functions as parameters to concurrently executing functions.
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() } -
Support passing function strings to dynamically import external libraries for concurrent computation.
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) }
Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
func | function | Yes | The parameter |
arg | string / number / bool / object / array / function / any (any type supported by the platform) | No | The parameter |
item | array | Yes | The parameter |
See Also
Remarks
The thread function func passed to the Thread() function for concurrent execution runs in an isolated environment, so it cannot directly reference variables outside the thread, which will cause compilation failure when referenced. Additionally, referencing other closure functions is not supported within the thread. All APIs provided by the platform can be called inside the thread, but user-defined functions cannot be called.
When a thread completes execution and is not continuously referenced, the system will automatically reclaim thread-related resources at the underlying level, without the need to explicitly call the join() function to release resources. If there are continuous references preventing resource release, an error will be reported when the number of concurrent threads exceeds 2000: InternalError: too many routine wait, max is 2000.
Supports backtesting system and live trading environment; all concurrent thread-related functions in the backtesting system are only provided for code compatibility support and will not actually execute concurrent threads, which will not be elaborated further in this chapter.
getThread
The getThread() function is used to get a thread object based on the specified thread ID.
getThread(threadId)Examples
Get the specified thread object by threadId.
javascript
function main() {
var t1 = threading.Thread(function () {
// Thread object has method: id(), used to get the thread's Id, you can check the documentation for the corresponding Thread object section
var id = threading.currentThread().id()
var thread1 = threading.getThread(id)
Log("id:", id, ", thread1.id():", thread1.id())
Log(`id == thread1.id():`, id == thread1.id())
})
t1.join()
}Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
threadId | number | Yes | The parameter |
See Also
Remarks
Supports backtesting system and live trading environment.
If the target thread has finished executing and been released, the thread object cannot be obtained through threading.getThread(threadId).
mainThread
The mainThread() function is used to get the thread object of the main thread, which is the thread where the main() function in the strategy is located.
mainThread()Examples
-
Get the
Threadobject of the main thread and output thethreadIdof the main thread.javascriptfunction main() { Log("Main thread ID:", threading.mainThread().id()) } -
The thread object of the main thread can also be obtained in concurrent threads.
javascriptfunction test() { Log("Main thread ID output in test function:", threading.mainThread().id()) } function main() { var t1 = threading.Thread(test) t1.join() }
Returns
| Type | Description |
| The |
See Also
Remarks
Supported in backtesting system and live trading environment.
currentThread
The currentThread() function is used to get the thread object of the current thread.
currentThread()Examples
Get the Thread object of the current thread and output the threadId of the current thread.
javascript
function test() {
Log("Current thread ID:", threading.currentThread().id())
}
function main() {
var t1 = threading.Thread(test)
t1.join()
}Returns
| Type | Description |
| The |
See Also
Remarks
Supports backtesting system and live trading environment.
Lock
The Lock() function is used to create a thread lock object.
Lock()Examples
Two concurrent threads accessing shared resources.
javascript
function consumer(productionQuantity, dict, lock) {
for (var i = 0; i < productionQuantity; i++) {
lock.acquire()
var count = dict.get("count")
Log("consumer:", count)
Sleep(1000)
lock.release()
}
}
function producer(productionQuantity, dict, lock) {
for (var i = 0; i < productionQuantity; i++) {
lock.acquire()
dict.set("count", i)
Log("producer:", i)
Sleep(1000)
lock.release()
}
}
function main() {
var dict = threading.Dict()
dict.set("count", -1)
var lock = threading.Lock()
var productionQuantity = 10
var producerThread = threading.Thread(producer, productionQuantity, dict, lock)
var consumerThread = threading.Thread(consumer, productionQuantity, dict, lock)
consumerThread.join()
producerThread.join()
}Returns
| Type | Description |
| The |
See Also
Remarks
Supports backtesting system and live trading environment.
Condition
The Condition() function is used to create a condition variable object, which is used to implement synchronization and communication between threads in a multi-threaded concurrent environment. Through Condition(), a thread can enter a waiting state when specific conditions are not met, until another thread signals that the conditions have been met.
Condition()Examples
Two concurrent threads accessing shared resources.
javascript
function consumer(productionQuantity, dict, condition) {
for (var i = 0; i < productionQuantity; i++) {
condition.acquire()
while (dict.get("array").length == 0) {
condition.wait()
}
var arr = dict.get("array")
var count = arr.shift()
dict.set("array", arr)
Log("consumer:", count, ", array:", arr)
condition.release()
Sleep(1000)
}
}
function producer(productionQuantity, dict, condition) {
for (var i = 0; i < productionQuantity; i++) {
condition.acquire()
var arr = dict.get("array")
arr.push(i)
dict.set("array", arr)
Log("producer:", i, ", array:", arr)
condition.notify()
condition.release()
Sleep(1000)
}
}
function main() {
var dict = threading.Dict()
dict.set("array", [])
var condition = threading.Condition()
var productionQuantity = 10
var producerThread = threading.Thread(producer, productionQuantity, dict, condition)
var consumerThread = threading.Thread(consumer, productionQuantity, dict, condition)
consumerThread.join()
producerThread.join()
}Returns
| Type | Description |
| The |
See Also
Remarks
The backtesting system does not currently support this feature, only the interface definition is provided.
Event
The Event() function is used to create a thread event object, which is used for synchronization between threads, allowing one thread to wait for notification or signal from another thread.
Event()Examples
Two concurrent threads accessing shared resources.
javascript
function consumer(productionQuantity, dict, pEvent, cEvent) {
for (var i = 0; i < productionQuantity; i++) {
while (dict.get("array").length == 0) {
pEvent.wait()
}
if (pEvent.isSet()) {
pEvent.clear()
}
var arr = dict.get("array")
var count = arr.shift()
dict.set("array", arr)
Log("consumer:", count, ", array:", arr)
cEvent.set()
Sleep(1000)
}
}
function producer(productionQuantity, dict, pEvent, cEvent) {
for (var i = 0; i < productionQuantity; i++) {
while (dict.get("array").length != 0) {
cEvent.wait()
}
if (cEvent.isSet()) {
cEvent.clear()
}
var arr = dict.get("array")
arr.push(i)
dict.set("array", arr)
Log("producer:", i, ", array:", arr)
pEvent.set()
Sleep(1000)
}
}
function main() {
var dict = threading.Dict()
dict.set("array", [])
var pEvent = threading.Event()
var cEvent = threading.Event()
var productionQuantity = 10
var producerThread = threading.Thread(producer, productionQuantity, dict, pEvent, cEvent)
var consumerThread = threading.Thread(consumer, productionQuantity, dict, pEvent, cEvent)
consumerThread.join()
producerThread.join()
}Returns
| Type | Description |
| The |
See Also
Remarks
Supports backtesting system and live trading environment.
Dict
The Dict() function is used to create a dictionary object for passing and sharing data between concurrent threads.
Dict()Examples
-
Pass a regular object to concurrent thread execution function, test whether modifying object key values will affect object key values in other threads.
javascriptfunction threadFun1(obj) { obj["age"] = 100 while (true) { Log("threadFun1 obj:", obj) Sleep(5000) } } function threadFun2(obj) { while (true) { Log("threadFun2 obj:", obj) Sleep(5000) } } function main() { var obj = {"age": 10} var t1 = threading.Thread(threadFun1, obj) var t2 = threading.Thread(threadFun2, obj) t1.join() t2.join() } -
Pass a
ThreadDictobject created by theDict()function to concurrent thread execution function, test whether modifying object key values will affect object key values in other threads.javascriptfunction threadFun1(threadDict) { threadDict.set("age", 100) while (true) { Log(`threadFun1 threadDict.get("age"):`, threadDict.get("age")) Sleep(5000) } } function threadFun2(threadDict) { while (true) { Log(`threadFun2 threadDict.get("age"):`, threadDict.get("age")) Sleep(5000) } } function main() { var threadDict = threading.Dict() threadDict.set("age", 10) var t1 = threading.Thread(threadFun1, threadDict) var t2 = threading.Thread(threadFun2, threadDict) t1.join() t2.join() }
Returns
| Type | Description |
| The |
See Also
Remarks
When passing regular objects to concurrent thread functions, deep copy is used. Modifying key values in concurrent threads will not affect dictionaries in other threads.
Supports backtesting system and live trading environment.
pending
The pending function is used to get the number of concurrent threads currently running in the strategy program.
pending()Examples
Create two concurrently running threads and call the pending() function at different time points.
javascript
function threadFun1() {
Log("threadFun1")
Sleep(3000)
}
function threadFun2() {
for (var i = 0; i < 3; i++) {
LogStatus(_D(), "print from threadFun2")
Sleep(3000)
}
}
function main() {
Log(`begin -- threading.pending():`, threading.pending())
var t1 = threading.Thread(threadFun1)
var t2 = threading.Thread(threadFun2)
Log(`after threading.Thread -- threading.pending():`, threading.pending())
t1.join()
t2.join()
Log(`after thread.join -- threading.pending():`, threading.pending())
}Returns
| Type | Description |
number | The |
See Also
Remarks
When the strategy's main() function starts running, directly calling pending() will return 1, because the main thread where main() function is located is also counted as a running thread.
Supports both backtesting system and live trading environment.
Thread
Thread objects can be created or returned through threading.Thread(), threading.getThread(), threading.mainThread(), threading.currentThread().
peekMessage
The peekMessage() function is used to receive messages from a thread.
peekMessage()
peekMessage(timeout)Examples
Concurrent thread sends messages to the main thread.
javascript
function main() {
var t1 = threading.Thread(function() {
for (var i = 0; i < 10; i++) {
Log("thread1 postMessage():", i)
threading.mainThread().postMessage(i)
Sleep(500)
}
})
while (true) {
var msg = threading.currentThread().peekMessage()
Log("main peekMessage():", msg)
if (msg == 9) {
break
}
Sleep(1000)
}
t1.join()
}Returns
| Type | Description |
string / number / bool / object / array / any (any type supported by the platform) | The |
Arguments
| Name | Type | Required | Description |
timeout | number | No | The |
See Also
Remarks
When writing programs, be careful to avoid thread deadlock issues.
postMessage
The postMessage() function is used to send messages to a thread.
postMessage(msg)Examples
-
Send messages in concurrent threads and use
eventLoop()to receive message notifications.javascriptfunction main() { var t1 = threading.Thread(function() { for (var i = 0; i < 10; i++) { Log("thread1 postMessage():", i) threading.mainThread().postMessage(i) Sleep(500) } }) for (var i = 0; i < 10; i++) { var event = threading.mainThread().eventLoop() Log("main event:", event) Sleep(500) } t1.join() } -
Supports sending functions.
javascriptfunction main() { threading.mainThread().postMessage(function(msg) { Log("func from mainThread, msg:", msg) }) threading.Thread(function() { var func = threading.mainThread().peekMessage() func("in " + threading.currentThread().name()) }).join() }
Arguments
| Name | Type | Required | Description |
msg | string / number / bool / object / array / function / any (any type supported by the platform) | Yes | The parameter |
See Also
Remarks
When the postMessage() function is called in a thread's execution function to send signals or data, it generates a message event. You can use the eventLoop() function to receive message notifications.
join
The join() function is used to wait for a thread to exit and reclaim system resources.
join()
join(timeout)Examples
Test join() function timeout and output the return value.
javascript
function main() {
var t1 = threading.Thread(function() {
Log("Hello thread1")
Sleep(5000)
})
var ret = t1.join(1000)
Log("ret:", ret) // ret: undefined
ret = t1.join()
Log("ret:", ret) // ret: {"id":1,"terminated":false,"elapsed":5003252000}
}Returns
| Type | Description |
| The
|
Arguments
| Name | Type | Required | Description |
timeout | number | No | The |
See Also
Remarks
When the join() function times out, it returns undefined.
terminate
The terminate() function is used to forcibly terminate a thread and release the hardware resources occupied when the thread was created.
terminate()Examples
Forcibly terminate the execution of a thread. After forcibly terminating the thread, the content output by that thread will no longer be displayed in the logs.
javascript
function main() {
var t1 = threading.Thread(function() {
for (var i = 0; i < 10; i++) {
Log("thread1 i:", i)
Sleep(1000)
}
})
Sleep(3000)
t1.terminate()
Log("after t1.terminate()")
while (true) {
LogStatus(_D())
Sleep(1000)
}
}See Also
Remarks
For threads forcibly terminated using the terminate() function, the join() function can no longer be used to wait for their completion.
getData
The getData() function is used to access variables recorded in the thread environment. The data is valid when the thread has not executed the join() function (waiting for successful exit) and has not executed the terminate() function (forcibly terminating the thread).
getData()
getData(key)Examples
Record a value with the key name count in the concurrent thread environment, then read the key value of count in the main thread.
javascript
function main() {
var t1 = threading.Thread(function() {
for (var i = 0; i < 5; i++) {
threading.currentThread().setData("count", i)
Log(`setData("count"):`, i)
Sleep(1000)
}
})
for (var i = 0; i < 5; i++) {
var count = threading.getThread(t1.id()).getData("count")
Log(`getData("count"):`, count)
Sleep(1000)
}
t1.join()
}Returns
| Type | Description |
string / number / bool / object / array / any (any type supported by the platform) | The |
Arguments
| Name | Type | Required | Description |
key | string | Yes | The |
See Also
setData
The setData() function is used to store variables in the thread environment.
setData(key, value)Examples
-
Set a key-value pair in a concurrent thread and read the key-value pair in the main thread.
javascriptfunction main() { var t1 = threading.Thread(function() { threading.currentThread().setData("data", 100) }) Sleep(1000) Log(`t1.getData("data"):`, t1.getData("data")) t1.join() } -
Supports passing functions as key values.
javascriptfunction main() { threading.mainThread().setData("func2", function(p) { Log("func2 p:", p) }) var t1 = threading.Thread(function() { threading.currentThread().setData("func1", function(p) { Log("func1 p:", p) }) var func2 = threading.mainThread().getData("func2") func2("test2") }) Sleep(1000) var func1 = t1.getData("func1") func1("test1") t1.join() }
Arguments
| Name | Type | Required | Description |
key | string | Yes | The |
value | string / number / bool / object / array / function / any (any type supported by the platform) | Yes | The |
See Also
Remarks
Data remains valid as long as the thread has not executed the join() function (waiting for successful exit) and has not executed the terminate() function (forcibly terminating the thread). The value parameter must be a serializable variable.
id
The id() function is used to return the threadId of the current multi-threaded object instance.
id()Examples
Create a concurrently running thread and output the threadId of that concurrent thread in the main thread.
javascript
function main() {
var t1 = threading.Thread(function() {
threading.currentThread().setData("data", 100)
})
Log(`t1.id():`, t1.id())
t1.join()
}Returns
| Type | Description |
number | The |
See Also
name
The name() function is used to return the name of the current multi-threaded object instance.
name()Examples
Create a concurrently running thread and output the name of that concurrent thread in the main thread.
javascript
function main() {
var t1 = threading.Thread(function() {
threading.currentThread().setData("data", 100)
})
Log(`t1.name():`, t1.name()) // t1.name(): Thread-1
t1.join()
}Returns
| Type | Description |
string | The |
See Also
eventLoop
The eventLoop() function is used to listen for events received by the thread.
eventLoop()
eventLoop(timeout)Examples
Execute 3 threads concurrently and output the received event information. When timeout occurs or immediate return, the output value is null.
javascript
function main() {
var t1 = threading.Thread(function() {
while (true) {
var eventMsg = threading.currentThread().eventLoop() // 阻塞等待
// 2024-11-14 10:14:18 thread1 eventMsg: {"Seq":1,"Event":"thread","ThreadId":0,"Index":1,"Queue":0,"Nano":1731550458699947000}
Log(_D(), "thread1 eventMsg:", eventMsg)
}
})
var t2 = threading.Thread(function() {
while (true) {
var eventMsg = threading.currentThread().eventLoop(-1) // 立即返回
Log(_D(), "thread2 eventMsg:", eventMsg)
Sleep(5000)
}
})
var t3 = threading.Thread(function() {
while (true) {
var eventMsg = threading.currentThread().eventLoop(3000) // 设置3秒超时
Log(_D(), "thread3 eventMsg:", eventMsg)
}
})
t1.postMessage("Hello ", t1.name())
t2.postMessage("Hello ", t2.name())
t3.postMessage("Hello ", t3.name())
t1.join()
t2.join()
t3.join()
}Returns
| Type | Description |
object / null | The |
Arguments
| Name | Type | Required | Description |
timeout | number | No | The parameter |
See Also
Remarks
The processing mechanism of the eventLoop() function is consistent with the global function EventLoop().
ThreadLock
Thread lock object for multi-threaded synchronization processing.
acquire
The acquire() function is used to request a thread lock (acquire lock).
acquire()Examples
Please refer to the threading.Lock() section for examples.
See Also
Remarks
The acquire() function is used to request a thread lock. When a thread calls the acquire() function of a thread lock object, it attempts to acquire the lock. If the lock is not currently held by another thread, the calling thread will successfully acquire the lock and continue execution. If the lock is already held by another thread, the thread calling acquire() will be blocked until the lock is released.
release
The release() function is used to release a thread lock (unlock).
release()Examples
Test deadlock scenario
javascript
function consumer(productionQuantity, dict, pLock, cLock) {
for (var i = 0; i < productionQuantity; i++) {
pLock.acquire()
cLock.acquire()
var arr = dict.get("array")
var count = arr.shift()
dict.set("array", arr)
Log("consumer:", count, ", array:", arr)
cLock.release()
Sleep(1000)
pLock.release()
}
}
function producer(productionQuantity, dict, pLock, cLock) {
for (var i = 0; i < productionQuantity; i++) {
cLock.acquire() // cLock.acquire() 放在 pLock.acquire() 后不会产生死锁
pLock.acquire()
var arr = dict.get("array")
arr.push(i)
dict.set("array", arr)
Log("producer:", i, ", array:", arr)
pLock.release()
Sleep(1000)
cLock.release()
}
}
function main() {
var dict = threading.Dict()
dict.set("array", [])
var pLock = threading.Lock()
var cLock = threading.Lock()
var productionQuantity = 10
var producerThread = threading.Thread(producer, productionQuantity, dict, pLock, cLock)
var consumerThread = threading.Thread(consumer, productionQuantity, dict, pLock, cLock)
consumerThread.join()
producerThread.join()
}See Also
Remarks
Note that improper use of thread locks may cause deadlocks.
ThreadEvent
Event object for event notification and signal passing between multiple threads.
set
The set() function is used to set an event signal.
set()Examples
Please refer to the examples in the threading.Event() section.
See Also
Remarks
If the event has already been set via set(), it cannot be set again. You need to call the clear operation first before resetting the signal.
clear
The clear() function is used to clear the signal.
clear()Examples
Please refer to the example in the threading.Event() section.
See Also
wait
The wait() function is used to set event (signal) waiting, which will block until the event (signal) is set; supports setting timeout parameters.
wait()
wait(timeout)Examples
Test the return value of the wait() function.
javascript
function main() {
var event = threading.Event()
var t1 = threading.Thread(function(event) {
var ret = event.wait(100)
Log(`event.wait(100):`, ret)
ret = event.wait()
Log(`event.wait():`, ret)
}, event)
Sleep(1000)
event.set()
t1.join()
}Returns
| Type | Description |
bool | The |
Arguments
| Name | Type | Required | Description |
timeout | number | No | The parameter |
See Also
isSet
The isSet() function is used to determine whether an event (signal) has been set.
isSet()Examples
Please refer to the examples in the threading.Event() section.
Returns
| Type | Description |
bool | The |
See Also
ThreadCondition
Condition variable object used for implementing synchronization and communication between multiple threads.
notify
The notify() function is used to wake up one waiting thread (if any exists). Only threads that have called the wait() method can be awakened.
notify()Examples
Use the notify() function to wake up waiting threads.
javascript
function consumer(dict, condition) {
while (true) {
condition.acquire()
while (dict.get("array").length == 0) {
Log(threading.currentThread().name(), "wait()...", ", array:", dict.get("array"))
condition.wait()
}
var arr = dict.get("array")
var num = arr.shift()
Log(threading.currentThread().name(), ", num:", num, ", array:", arr, "#FF0000")
dict.set("array", arr)
Sleep(1000)
condition.release()
}
}
function main() {
var condition = threading.Condition()
var dict = threading.Dict()
dict.set("array", [])
var t1 = threading.Thread(consumer, dict, condition)
var t2 = threading.Thread(consumer, dict, condition)
var t3 = threading.Thread(consumer, dict, condition)
Sleep(1000)
var i = 0
while (true) {
condition.acquire()
var msg = ""
var arr = dict.get("array")
var randomNum = Math.floor(Math.random() * 5) + 1
if (arr.length >= 3) {
condition.notifyAll()
msg = "notifyAll"
} else {
arr.push(i)
dict.set("array", arr)
if (randomNum > 3 && arr.length > 0) {
condition.notify()
msg = "notify"
} else {
msg = "pass"
}
i++
}
Log(_D(), "randomNum:", randomNum, ", array:", arr, ", msg:", msg)
condition.release()
Sleep(1000)
}
}See Also
Remarks
The notify() function wakes up one thread in the waiting queue.
When the notify() function wakes up a thread, that thread will reacquire the thread lock.
notifyAll
The notifyAll() function is used to wake up all waiting threads.
notifyAll()Examples
For examples, please refer to the ThreadCondition.notify() section.
See Also
Remarks
The notifyAll() function wakes up all threads in the waiting state one by one, and the awakened threads will reacquire the thread lock.
wait
The wait() function is used to put a thread into a waiting state under specific conditions.
wait()Examples
For examples, please refer to the content in the ThreadCondition.notify() section.
See Also
Remarks
The wait() function releases the thread lock and will reacquire the thread lock when the thread is awakened.
acquire
The acquire() function is used to request a thread lock (acquire lock).
acquire()Examples
For examples, please refer to the content in the ThreadCondition.notify() section.
See Also
Remarks
The thread lock of the current condition object must be requested (acquired) before calling wait().
ThreadDict
Thread-safe dictionary object for data sharing in multi-threaded environments.
get
The get() function is used to retrieve the value of a key recorded in a dictionary object.
get(key)Examples
Use event objects to notify threads to read and modify data.
javascript
function main() {
var event = threading.Event()
var dict = threading.Dict()
dict.set("data", 100)
var t1 = threading.Thread(function(dict, event) {
Log(`thread1, dict.get("data"):`, dict.get("data"))
event.set()
event.clear()
event.wait()
Log(`after main change data, thread1 dict.get("data"):`, dict.get("data"))
dict.set("data", 0)
}, dict, event)
event.wait()
dict.set("data", 99)
event.set()
event.clear()
t1.join()
Log(`main thread, dict.get("data"):`, dict.get("data"))
}Returns
| Type | Description |
string / number / bool / object / array / any (any type supported by the platform) | The |
Arguments
| Name | Type | Required | Description |
key | string | Yes | The |
See Also
set
The set() function is used to set key-value pairs.
set(key, value)Examples
Supports passing functions as key values.
javascript
function main() {
var dict1 = threading.Dict()
dict1.set("func1", function(p) {
Log("func1 p:", p)
})
threading.Thread(function(dict1) {
var func1 = dict1.get("func1")
func1("test")
}, dict1).join()
}Arguments
| Name | Type | Required | Description |
key | string | Yes | The |
value | string / number / bool / object / array / function / any (any type supported by the platform) | Yes | The |
See Also