The __threadJoin()
function is used to wait for the thread with the specified Id to exit (the Id returned by the __Thread()
function) and to reclaim system resources.
The __threadJoin()
function returns an object containing the data associated with the execution result, structured as follows:
{
"id":1, // Thread Id
"terminated":false, // Whether the thread is forced to end
"elapsed":2504742813, // Running time of the thread (nanoseconds)
"ret": 123 // The return value of the thread function
}
object, null value
__threadJoin(threadId) __threadJoin(threadId, timeout)
The threadId
parameter is used to specify the id of the waiting thread.
threadId
true
number
The timeout
parameter is used to set the timeout in milliseconds to wait for the thread to finish. The __threadJoin()
function blocks when the timeout
parameter is set to 0 or when the timeout
parameter is not set, and waits until the thread has finished executing. The __threadJoin()
function returns immediately when the timeout
parameter is set to -1.
timeout
false
number
function testFunc() {
for (var i = 0 ; i < 5 ; i++) {
Log(i)
Sleep(300)
}
}
function main() {
var id = __Thread(testFunc)
Log(__threadJoin(id, 1000))
Log(__threadJoin(id))
}
The following code tests the timeout mechanism of the __threadJoin()
function.
function testFunc1() {
for (var i = 0; i < 10; i++) {
Log("testFunc1", i)
Sleep(1000)
}
}
function testFunc2(tid) {
for (var i = 0; i < 10; i++) {
if (i == 5) {
__threadTerminate(tid)
Log("Terminate the thread, tid:", tid)
}
Sleep(1000)
}
}
function main() {
var id1 = __Thread(testFunc1)
var id2 = __Thread(testFunc2, id1)
var ret1 = __threadJoin(id1)
Log("ret1:", ret1)
var ret2 = __threadJoin(id2)
Log("ret2:", ret2)
}
The following code tests the scenario where the __threadJoin()
function and the __threadTerminate()
function are called at the same time.
The __threadJoin()
function times out and returns undefined
.
{@fun/Threads/__Thread __Thread}, {@fun/Threads/__threadPeekMessage __threadPeekMessage}, {@fun/Threads/__threadPostMessage __threadPostMessage}, {@fun/Threads/__threadTerminate __threadTerminate}, {@fun/Threads/__threadGetData __threadGetData}, {@fun/Threads/__threadSetData __threadSetData}, {@fun/Threads/__threadId __threadId}, {@fun/Threads/__threadPending __threadPending}
__threadPostMessage __threadTerminate