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.