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

ThreadLock

线程锁对象,用于多线程同步处理。

acquire

acquire()函数用于请求一个线程锁(加锁)。

acquire()

范例可以参考threading.Lock()章节的内容。

acquire()函数用于请求一个线程锁。当一个线程调用某个线程锁对象的acquire()函数时,它会尝试获取锁,如果锁当前没有被其它线程占用,调用线程就会成功获得锁并继续执行。如果锁已经被其它线程持有,调用acquire()的线程会被阻塞,直到锁被释放。

{@fun/Threads/threading/Lock Lock}, {@fun/Threads/ThreadLock/release release}

release

release()函数用于释放一个线程锁(解锁)。

release()

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

测试死锁场景

需要注意,线程锁使用不当可能导致死锁。

{@fun/Threads/threading/Lock Lock}, {@fun/Threads/ThreadLock/acquire acquire}

Thread ThreadEvent