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