資源の読み込みに... 荷物...

スレッド



### Thread

```Thread()```函数用于创建并发线程。


```Thread()```函数返回一个```Thread```对象,用于管理创建出的并发线程、线程通信等。

```Thread```对象


Thread(func, ...args)
Thread(...items)

参数```func```是用于并发执行的函数(通过引用传递),支持传入匿名函数。```func```可接受多个参数,这些参数将在并发执行时通过```...args```传入。因此,```func```的参数列表需要与```...args```一致。

func
true
function
参数```arg```是在回调执行时传递给```func```(即并发线程执行函数)的实际参数;参数```arg```可能有多个,```func```的参数列表需要与```...args```一致。

arg
false
string、number、bool、object、array、function、空值等系统支持的所有类型
参数```item```是一个数组,包含待并发执行的函数引用及其参数,调用```Thread```函数时的参数```item```可以传入多组。

item
true
array

```javascript
function test1(a, b, c) {
    Log("test1:", a, b, c)
}

function main() {
    var t1 = threading.Thread(test1, 1, 2, 3)
    var t2 = threading.Thread(function (msg) {
        Log("msg:", msg)
    }, "Hello thread2")

    t1.join()
    t2.join()
}

既定関数と匿名関数の両方の並行スレッドを同時に作成する.

function test1(msg) {
    Log("msg:", msg)
    test2("Hello test2")
}

function main() {
    var t1 = threading.Thread(
        [function(a, b, c) {Log(a, b, c)}, 1, 2, 3], 
        [test1, "Hello test1"], 
        [`function test2(msg) {Log("msg:", msg)}`])

    t1.join()
}

使用するThread(...items)形式は,複数の関数を順序で実行する並行スレッドを作成します.

function testFunc1(p) {
    Log("testFunc1 p:", p)
}

function main() {
    threading.Thread(function(pfn) {
        var threadName = threading.currentThread().name()
        var threadId = threading.currentThread().id()
        pfn(`in thread threadName: ${threadName}, threadId: ${threadId}`)
    }, testFunc1).join()
}

同期実行する関数への参数伝達関数をサポートする.

function ml(input) {
    const net = new brain.NeuralNetwork()
    net.train([
        { input: [0, 0], output: [0] },
        { input: [0, 1], output: [1] },
        { input: [1, 0], output: [1] },
        { input: [1, 1], output: [0] },
    ])
    return net.run(input)
}

function main() {
    var ret = threading.Thread([ml, [1, 0]], [HttpQuery("https://unpkg.com/brain.js")]).join()

    // ret: {"id":1,"terminated":false,"elapsed":337636000,"ret":{"0":0.9339330196380615}}
    Log(ret)
}

入力函数の文字列をサポートし,動的に外部データベースにインポートして並行計算できます.

感染Thread()関数は同時に実行されるスレッド関数ですfunc孤立した環境で実行されるため,スレッドの外部の変数を直接引用することができないため,引用時にコンパイル失敗する.同時に,スレッド内では他の閉じる関数を引用するサポートがありません.スレッド内ではプラットフォームが提供するすべてのAPIを呼び出すことができますが,ユーザーにカスタマイズされた他の関数を呼び出すことはできません.

文字列が実行完了し,継続的に参照されていないとき,システム底層は,明示的な呼び出しを必要とせず,文字列に関連するリソースを自動的に回収します.join()関数はリソースを解放します. 連続した参照がリソースを解放できない場合,並行数が2000を超える場合はエラーが返されます:InternalError: too many routine wait, max is 2000

復習システム,実盤環境をサポートする.すべての並行スレッドに関連する関数は,復習システムでのコード互換性サポートのみで,実際には並行スレッドが実行されない.この章は,これ以上説明しない.

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

getThread を取得する



```getThread()```函数返回通过参数指定threadId的```Thread```对象

```Thread```对象


getThread(threadId)

参数```threadId```为线程对象Id,通过指定参数获取对应的线程对象。

threadId
true
number

```javascript
function main() {
    var t1 = threading.Thread(function () {
        // Thread 对象有方法:id(),用于获取线程的Id,可以查看文档对应Thread对象的章节
        var id = threading.currentThread().id()
        var thread1 = threading.getThread(id)
        
        Log("id:", id, ", thread1.id():", thread1.id())
        Log(`id == thread1.id():`, id == thread1.id())
    })
    t1.join()
}

通過threadId指定されたスレッドオブジェクトを取得します.

復習システム,リアルディスク環境をサポートします.

取得したいスレッドが実行完了,解放されている場合,この時点で通過できません.threading.getThread(threadId)このスレッドのスレッドオブジェクトを取得します.

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

メインスレッド



```mainThread()```函数返回主线程的线程对象。

```Thread```对象


mainThread()

```javascript
function main() {
    Log("主线程的threadId:", threading.mainThread().id())
}

主なスレッドを入手するThread文字列を表示するthreadId

function test() {
    Log("test函数中输出主线程Id:", threading.mainThread().id())
}

function main() {
    var t1 = threading.Thread(test)
    t1.join()
}

同期スレッドでは主スレッドのスレッドオブジェクトも取得できます.

復習システム,リアルディスク環境をサポートします.

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

currentスレッド



```currentThread()```函数返回当前线程的线程对象。

```Thread```对象


currentThread()

```javascript
function test() {
    Log("当前线程的Id:", threading.currentThread().id())
}

function main() {
    var t1 = threading.Thread(test)
    t1.join()
}

このページでは,Thread文字列を入力します.threadId

復習システム,リアルディスク環境をサポートします.

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

ロック



```Lock()```函数返回一个线程锁对象。

```ThreadLock```对象


Lock()

```javascript
function consumer(productionQuantity, dict, lock) {
    for (var i = 0; i < productionQuantity; i++) {
        lock.acquire()
        var count = dict.get("count")        
        Log("consumer:", count)
        Sleep(1000)
        lock.release()
    }
}

function producer(productionQuantity, dict, lock) {
    for (var i = 0; i < productionQuantity; i++) {
        lock.acquire()
        dict.set("count", i)
        Log("producer:", i)
        Sleep(1000)
        lock.release()
    }
}

function main() {
    var dict = threading.Dict()
    dict.set("count", -1)
    var lock = threading.Lock()
    var productionQuantity = 10
    var producerThread = threading.Thread(producer, productionQuantity, dict, lock)
    var consumerThread = threading.Thread(consumer, productionQuantity, dict, lock)

    consumerThread.join()
    producerThread.join()
}

公共資源へのアクセスには2つの並行線があります.

復習システム,リアルディスク環境をサポートします.

{@fun/Threads/threading/getThread getThread}, {@fun/Threads/threading/mainThread mainThread}, {@fun/Threads/threading/currentThread currentThread}, {@fun/Threads/threads/threading/Thread Thread}, {@fun/Threads/threads/threading/condition Condition}, {@fun/Threads/threads/threading/event Event}, {@fun/Threads/threads/threading/mainThread mainThread}, {@fun/Threads/threads/threading/currentThread currentThread}, {@fun/Threads/threads/threading/threads/threading/threadThreadThread}, {@fun/Threads/threads/threads/threads/threads/eventLoopイベント}, {@fun/Threads/threads/threads/thre

条件



```Condition()```函数返回一个```ThreadCondition```对象。

```ThreadCondition```对象


Condition()

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

公共資源へのアクセスには2つの並行線があります.

復習システムは,この機能を実装していない.

{@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/threads/mainThread mainThread}, {@fun/Threads/threads/threading/currentThread currentThread}, {@fun/Threads/threads/threads/threading/Loop lock}, {@fun/Threads/threads/threads/eventLoop}, {@fun/Threads/threads/threads/threading/eventLoop}, {@fun/Threads/threads/th

イベント



```Event()```函数返回一个```ThreadEvent```对象。

```ThreadEvent```对象


Event()

```javascript
function consumer(productionQuantity, dict, pEvent, cEvent) {
    for (var i = 0; i < productionQuantity; i++) {
        while (dict.get("array").length == 0) {
            pEvent.wait()
        }
        if (pEvent.isSet()) {
            pEvent.clear()
        }

        var arr = dict.get("array")
        var count = arr.shift()
        dict.set("array", arr)
        Log("consumer:", count, ", array:", arr)
        cEvent.set()
        Sleep(1000)
    }
}

function producer(productionQuantity, dict, pEvent, cEvent) {
    for (var i = 0; i < productionQuantity; i++) {
        while (dict.get("array").length != 0) {
            cEvent.wait()
        }
        if (cEvent.isSet()) {
            cEvent.clear()
        }

        var arr = dict.get("array")
        arr.push(i)
        dict.set("array", arr)
        Log("producer:", i, ", array:", arr)        
        pEvent.set()       
        Sleep(1000)
    }
}

function main() {    
    var dict = threading.Dict()
    dict.set("array", [])
    var pEvent = threading.Event()
    var cEvent = threading.Event()
    var productionQuantity = 10
    var producerThread = threading.Thread(producer, productionQuantity, dict, pEvent, cEvent)
    var consumerThread = threading.Thread(consumer, productionQuantity, dict, pEvent, cEvent)

    consumerThread.join()
    producerThread.join()
}

公共資源へのアクセスには2つの並行線があります.

復習システム,リアルディスク環境をサポートします.

{@fun/Threads/threading/getThread getThread}, {@fun/Threads/threading/mainThread mainThread}, {@fun/Threads/threading/currentThread currentThread}, {@fun/Threads/threading/Lock Lock}, {@fun/Threads/threading/Condition Condition}, {@fun/Threads/threading/Thread Thread}, {@fun/Threads/threads/threading/Dict Dict}, {@fun/Threads/threading/pending pending}, {@fun/Threads/threads/threading/eventLoop 事件終了}

ディクト



```Dict()```函数返回一个```ThreadDict```对象。

```ThreadDict```对象


Dict()

```javascript
function threadFun1(obj) {
    obj["age"] = 100
    while (true) {
        Log("threadFun1 obj:", obj)
        Sleep(5000)
    }
}

function threadFun2(obj) {
    while (true) {
        Log("threadFun2 obj:", obj)
        Sleep(5000)
    }
}

function main() {
    var obj = {"age": 10}
    var t1 = threading.Thread(threadFun1, obj)
    var t2 = threading.Thread(threadFun2, obj)
    t1.join()
    t2.join()    
}

同期スレッドに実行関数を普通オブジェクトに転送し,オブジェクトのキー値を修正すると,他のスレッドのオブジェクトのキー値が変化するかどうかをテストする.

function threadFun1(threadDict) {
    threadDict.set("age", 100)
    while (true) {
        Log(`threadFun1 threadDict.get("age"):`, threadDict.get("age"))
        Sleep(5000)
    }
}

function threadFun2(threadDict) {
    while (true) {
        Log(`threadFun2 threadDict.get("age"):`, threadDict.get("age"))
        Sleep(5000)
    }
}

function main() {
    var threadDict = threading.Dict()
    threadDict.set("age", 10)
    var t1 = threading.Thread(threadFun1, threadDict)
    var t2 = threading.Thread(threadFun2, threadDict)

    t1.join()
    t2.join()    
}

同期スレッドに実行関数を送信するDict()函数によって作成されたThreadDictオブジェクト,オブジェクトのキー値を変更した後に他のスレッドのオブジェクトキー値が変化するかどうかをテストする.

文字列の並列関数は,通常のオブジェクトへの伝達時に,深複製に伝達され,並列文字列内のキー値を修正し,他の文字列の辞書に影響を与えません.

復習システム,リアルディスク環境をサポートします.

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

待機中



```pending()```函数返回当前策略程序正在运行的并发线程数。

number

pending()

```javascript
function threadFun1() {
    Log("threadFun1")
    Sleep(3000)
}

function threadFun2() {
    for (var i = 0; i < 3; i++) {
        LogStatus(_D(), "print from threadFun2")
        Sleep(3000)
    }
}

function main() {
    Log(`begin -- threading.pending():`, threading.pending())

    var t1 = threading.Thread(threadFun1)
    var t2 = threading.Thread(threadFun2)
    Log(`after threading.Thread -- threading.pending():`, threading.pending())

    t1.join()
    t2.join()
    Log(`after thread.join -- threading.pending():`, threading.pending())
}

異なる時間帯でノードを呼び出すために,同時に実行する2つのスレッドを作成しますpending()この関数は,

戦略main()実行開始時に直接呼び出すpending()この関数は1を返します.main()函数にあるメインスレッドは,また,待機中のスレッドである.

復習システム,リアルディスク環境をサポートします.

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

ネットワーク設定 スレッド