Sumber dimuat naik... memuat...

Keadaan

PeraturanCondition()fungsi digunakan untuk membuat objek pembolehubah keadaan, yang digunakan untuk mencapai penyegerakan dan komunikasi antara benang dalam persekitaran serentak berbilang benang.Condition(), benang boleh menunggu apabila keadaan tertentu tidak dipenuhi sehingga benang lain memaklumkan bahawa keadaan telah dipenuhi.

PeraturanCondition()fungsi mengembalikan aThreadCondition object.

ThreadConditionobjek

Keadaan

function consumer(productionQuantity, dict, condition) {
    for (var i = 0; i < productionQuantity; i++) {
        condition.acquire()
        while (dict.get("array").length == 0) {
            condition.wait()
        }
        var arr = dict.get("array")
        var count = arr.shift()
        dict.set("array", arr)
        Log("consumer:", count, ", array:", arr)
        condition.release()
        Sleep(1000)
    }
}

function producer(productionQuantity, dict, condition) {
    for (var i = 0; i < productionQuantity; i++) {
        condition.acquire()
        var arr = dict.get("array")
        arr.push(i)
        dict.set("array", arr)
        Log("producer:", i, ", array:", arr)
        condition.notify()
        condition.release()
        Sleep(1000)
    }
}

function main() {
    var dict = threading.Dict()
    dict.set("array", [])
    var condition = threading.Condition()
    var productionQuantity = 10
    var producerThread = threading.Thread(producer, productionQuantity, dict, condition)
    var consumerThread = threading.Thread(consumer, productionQuantity, dict, condition)
    consumerThread.join()
    producerThread.join()
}

Dua benang serentak mengakses sumber yang sama.

Sistem backtesting tidak melaksanakan fungsi ini, ia hanya mentakrifkannya.

{@fun/Threads/getThread getThread}, {@fun/Threads/threads/mainThread mainThread}, {@fun/Threads/threading/currentThread currentThread}, {@fun/Threads/threads/threading/Lock Lock}, {@fun/Threads/threads/threading/Thread Thread}, {@fun/Threads/threads/threading/Event Event}, {@fun/Threads/threads/threading/Dict Dict}, {@fun/Threads/threading/threading/pending pending}, {@fun/Threads/threading/eventLoop}

Kunci Acara