资源加载中... loading...

Thread

Thread objects can be created or returned by threading.Thread(), threading.getThread(), threading.mainThread(), and threading.currentThread().

peekMessage

The peekMessage() function is used to get a message from a thread.

The peekMessage() function returns the message received by the thread associated with the current thread object.

string, number, bool, object, array, null value and other types supported by the system

peekMessage() peekMessage(timeout)

The parameter timeout is the timeout setting. It will block and wait for the number of milliseconds set by the parameter and return data. If there is no data and the timeout exceeds the limit, a null value will be returned. If timeout is set to 0 or the timeout parameter is not passed, it means that the process will block and wait until data is received from the channel. If timeout is set to -1, it means that the process will not block and return data immediately. If there is no data, a null value will be returned.

timeout false number

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()
}

Send messages to the main thread from a concurrent thread.

When writing programs, we need to pay attention to thread deadlock problems.

{@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name}, {@fun/Threads/Thread/eventLoop eventLoop}

postMessage

The postMessage() function is used to send a message to a thread.

postMessage(msg)

The parameter msg is the message to be sent.

msg true Any type supported by the system, such as string, number, bool, object, array, function, null value, etc.

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

Send messages in concurrent threads and use eventLoop() to receive message notifications.

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

It supports sending a function.

When a thread’s execution function calls the postMessage() function to send a signal or data, a message event is also generated. We can use the eventLoop() function to receive message notifications.

{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name}, {@fun/Threads/Thread/eventLoop eventLoop}

join

The join() function is used to wait for the thread to exit and reclaim system resources.

The ThreadRet object contains data about the execution result. The properties include the following:

  • id: Thread Id.
  • terminated: Whether the thread is forced to end.
  • elapsed: The running time of the thread in nanoseconds.
  • ret: The return value of the thread function.

ThreadRet object

join() join(timeout)

The timeout parameter is used to set the timeout in milliseconds for waiting for the thread to finish. When the timeout parameter is set to 0 or the timeout parameter is not set, the join() function will block and wait until the thread finishes executing. When the timeout parameter is set to -1, the join() function will return immediately.

timeout false number

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}
}

Test the join() function for timeout and output the return value.

The join() function times out and returns undefined.

{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name}, {@fun/Threads/Thread/eventLoop eventLoop}

terminate

The terminate() function is used to forcibly terminate a thread and release the hardware resources used by the created thread.

terminate()

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

Terminate the execution of a thread forcefully. After forcibly terminating a thread, there will be no output from this thread in the log.

For threads that are forcibly terminated by the terminate() function, we can no longer use the join() function to wait for them to terminate.

{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name}, {@fun/Threads/Thread/eventLoop eventLoop}

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 exit success) and has not executed the terminate() function (terminating the thread forcibly).

The getData() function returns the key value corresponding to the key parameter in the key-value pair stored in the current thread context.

string, number, bool, object, array, null value and other types supported by the system

getData() getData(key)

The key parameter is the key name of the stored key-value pair.

key true string

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()
}

Record the value of the key count in the concurrent thread environment, and then read the key value of count in the main thread.

{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name}, {@fun/Threads/Thread/eventLoop eventLoop}

setData

The setData() function is used to store variables in the thread context.

setData(key, value)

The key parameter is used to specify the key name of the stored key-value pair.

key true string The value parameter is used to specify the key value of the stored key-value pair.

value true Any type supported by the system, such as string, number, bool, object, array, function, null value, etc.

function main() {
    var t1 = threading.Thread(function() {
        threading.currentThread().setData("data", 100)
    })
    Sleep(1000)
    Log(`t1.getData("data"):`, t1.getData("data"))
    t1.join()
}

Set the key-value pair in the concurrent thread and read the key-value pair in the main thread.

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

It supports key-value passing into functions.

The data is valid when the thread has not executed the join() function (waiting for exit success) and has not executed the terminate() function (terminating the thread forcibly). The value of the parameter value must be a serializable variable.

{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name}, {@fun/Threads/Thread/eventLoop eventLoop}

id

The id() function is used to return the threadId of the current multithreaded object instance.

The return value of the id() function is threadId.

number

id()

function main() {
    var t1 = threading.Thread(function() {
        threading.currentThread().setData("data", 100)
    })
    Log(`t1.id():`, t1.id())
    t1.join()
}

Create a concurrently running thread and output the threadId of this concurrent thread in the main thread.

{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/name name}, {@fun/Threads/Thread/eventLoop eventLoop}

name

The name() function is used to return the name of the current multithreaded object instance.

The name() function returns the concurrent thread name.

string

name()

function main() {
    var t1 = threading.Thread(function() {
        threading.currentThread().setData("data", 100)
    })
    Log(`t1.name():`, t1.name())  // t1.name(): Thread-1
    t1.join()
}

Create a concurrent thread and output the name of the concurrent thread in the main thread.

{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/eventLoop eventLoop}

eventLoop

The eventLoop() function is used to listen for events received by the thread.

The eventLoop() function returns the event information received by the current thread. See Event Information Structure.

object, null value

eventLoop() eventLoop(timeout)

The parameter timeout is the timeout setting in milliseconds. If the parameter timeout is set to 0, it will wait for an event to occur before returning. If it is greater than 0, it will set the event waiting timeout. If it is less than 0, it will return the latest event immediately.

timeout false number

function main() {
    var t1 = threading.Thread(function() {
        while (true) {
            var eventMsg = threading.currentThread().eventLoop()     // Blocking wait
            // 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)   // Return immediately
            Log(_D(), "thread2 eventMsg:", eventMsg)
            Sleep(5000)
        }
    })

    var t3 = threading.Thread(function() {
        while (true) {
            var eventMsg = threading.currentThread().eventLoop(3000) // Set a 3 second timeout
            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()
}

Execute three threads concurrently and output the received event information. If the timeout occurs or the function returns immediately, the output value is null.

The processing mechanism of the eventLoop() function is the same as the global function EventLoop().

{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name}

threading ThreadLock