発明者は,量子取引プラットフォームをシステム底部から本当にサポートしています.JavaScript
言語戦略の多糸機能は,次のオブジェクトを実現します:
オブジェクト | 解説 | コメント |
---|---|---|
スレッド | マルチスレッドグローバルオブジェクト | メンバー関数:Thread 、getThread 、mainThread ほら |
スレッド | スレッドオブジェクト | メンバー関数:peekMessage 、postMessage 、join ほら |
スレッドロック | スレッドロックオブジェクト | メンバー関数:acquire 、release ┃ 文字列の実行関数として文字列の環境に参数を送信する。 |
ThreadEvent について | 事件の対象 | メンバー関数:set 、clear 、wait 、isSet ┃ 文字列の実行関数として文字列の環境に参数を送信する。 |
ThreadCondition について | 条件対象 | メンバー関数:notify 、notifyAll 、wait 、acquire 、release ┃ 文字列の実行関数として文字列の環境に参数を送信する。 |
ThreadDict について | 辞書オブジェクト | メンバー関数:get 、set ┃ 文字列の実行関数として文字列の環境に参数を送信する。 |
### 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()```函数返回通过参数指定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}
```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}
### peekMessage
```peekMessage()```函数用于从线程获取消息。
```peekMessage()```函数返回当前线程对象关联的线程收到的消息。
string、number、bool、object、array、空值等系统支持的所有类型
peekMessage()
peekMessage(timeout)
参数```timeout```为超时设置,会按照该参数设置的毫秒数阻塞等待,返回数据;没有数据并且超时则返回空值。如果```timeout```设置为0或者不传```timeout```参数,则表示一直阻塞等待,直到接收到通道中的数据。如果```timeout```设置为-1,则表示不阻塞并且立即返回数据,没有数据时返回空值。
timeout
false
number
```javascript
function main() {
var t1 = threading.Thread(function() {
for (var i = 0; i < 10; i++) {
Log("thread1 postMessage():", i)
threading.mainThread().postMessage(i)
Sleep(500)
}
})
while (true) {
var msg = threading.currentThread().peekMessage()
Log("main peekMessage():", msg)
if (msg == 9) {
break
}
Sleep(1000)
}
t1.join()
}
配線線で主線にメッセージを送信する.
プログラムを書くときに注意すべきことは,スレッドデッドロックの問題である.
{@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/join name}, {@fun/Threads/Thread/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop}, {@fun/Threads/Threads/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop}, {@fun/Threads/event
postMessage(msg)
参数```msg```为所要发送的消息。
msg
true
string、number、bool、object、array、function、空值等系统支持的任意类型
```javascript
function main() {
var t1 = threading.Thread(function() {
for (var i = 0; i < 10; i++) {
Log("thread1 postMessage():", i)
threading.mainThread().postMessage(i)
Sleep(500)
}
})
for (var i = 0; i < 10; i++) {
var event = threading.mainThread().eventLoop()
Log("main event:", event)
Sleep(500)
}
t1.join()
}
メッセージを送信し,使います.eventLoop()
ニュースの通知を受け取る.
function main() {
threading.mainThread().postMessage(function(msg) {
Log("func from mainThread, msg:", msg)
})
threading.Thread(function() {
var func = threading.mainThread().peekMessage()
func("in " + threading.currentThread().name())
}).join()
}
函数を送信するサポート.
実行関数に呼び出します.postMessage()
函数が信号,データを送信するときにメッセージイベントも発生します.eventLoop()
機能はメッセージ通知を受け取ります.
{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData set}, {@fun/Threads/Thread/id id}, {@fun/Threads/Threads/Thread/name name join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Threads/id id}, {@fun/Threads/Threads/Threads/name name}, {@fun/Threads/Thread/eventLoop eventLoop}
[```ThreadRet```对象](https://www.fmz.com/syntax-guide/struct/otherstruct/Thread.join-return)包含执行结果的相关数据,包含的属性如下:
- id: 线程Id。
- terminated: 线程是否被强制结束。
- elapsed: 线程的运行时间(纳秒)。
- ret: 线程函数的返回值。
```ThreadRet```对象
join()
join(timeout)
```timeout```参数用于设置等待线程结束的超时时间,单位为毫秒。```timeout```参数设置为0或者不设置```timeout```参数时```join()```函数会阻塞,等待到线程执行结束。```timeout```参数设置为-1时,```join()```函数会立即返回。
timeout
false
number
```javascript
function main() {
var t1 = threading.Thread(function() {
Log("Hello thread1")
Sleep(5000)
})
var ret = t1.join(1000)
Log("ret:", ret) // ret: undefined
ret = t1.join()
Log("ret:", ret) // ret: {"id":1,"terminated":false,"elapsed":5003252000}
}
テストjoin()
函数が終了すると,出力値が返されます.
{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name}, {@fun/Threads/Thread/eventLoop eventLoop}
### terminate
```terminate()```函数用于强制结束线程,释放创建线程使用的硬件资源。
terminate()
```javascript
function main() {
var t1 = threading.Thread(function() {
for (var i = 0; i < 10; i++) {
Log("thread1 i:", i)
Sleep(1000)
}
})
Sleep(3000)
t1.terminate()
Log("after t1.terminate()")
while (true) {
LogStatus(_D())
Sleep(1000)
}
}
強制的にスレッドの実行を終了させ,スレッドを強制的に終了した後,ログにはそのスレッドの出力が含まれていない.
についてterminate()
函数で強制的に終了したスレッドは,もはや使用できません.join()
函数終了を待っています.
{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Threads/Thread/name name}, {@fun/Threads/Threads/Thread/eventLoop eventLoop}, {@fun/Threads/Threads/eventLoop eventLoop}, {@fun/Threads/Threads/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop event
```getData()```函数返回当前线程环境中储存的键-值对中```key```参数对应的键值。
string、number、bool、object、array、空值等系统支持的所有类型
getData()
getData(key)
```key```参数为储存的键-值对的键名。
key
true
string
```javascript
function main() {
var t1 = threading.Thread(function() {
for (var i = 0; i < 5; i++) {
threading.currentThread().setData("count", i)
Log(`setData("count"):`, i)
Sleep(1000)
}
})
for (var i = 0; i < 5; i++) {
var count = threading.getThread(t1.id()).getData("count")
Log(`getData("count"):`, count)
Sleep(1000)
}
t1.join()
}
文字列の文字列を書き換えるcount
文字列の文字列の文字列の文字列をcount
キー値は,
{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/setData set}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name name}, {@fun/Threads/Thread/thread/eventLoop eventLoop}, {@fun/Threads/Threads/eventLoop eventLoop}, {@fun/Threads/Thread/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop}, {@fun/Threads/thread/eventLoop eventLoop eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop}, {@fun/Threads
setData(key, value)
```key```参数用于指定储存的键-值对的键名。
key
true
string
```value```参数用于指定储存的键-值对的键值。
value
true
string、number、bool、object、array、function、空值等系统支持的任意类型
```javascript
function main() {
var t1 = threading.Thread(function() {
threading.currentThread().setData("data", 100)
})
Sleep(1000)
Log(`t1.getData("data"):`, t1.getData("data"))
t1.join()
}
同行スレッドにキー値対を設定し,メインスレッドでこのキー値対を読み取る.
function main() {
threading.mainThread().setData("func2", function(p) {
Log("func2 p:", p)
})
var t1 = threading.Thread(function() {
threading.currentThread().setData("func1", function(p) {
Log("func1 p:", p)
})
var func2 = threading.mainThread().getData("func2")
func2("test2")
})
Sleep(1000)
var func1 = t1.getData("func1")
func1("test1")
t1.join()
}
キー値伝達関数もサポートします.
データのスレッドが実行されていないjoin()
関数 ((退出成功待ち) が実行されていないterminate()
関数 (強制終了スレッド) の場合有効である.value
順序付け可能な変数である必要があります.
{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name}, {@fun/Threads/Threads/Thread/eventLoop eventLoop}, {@fun/Threads/Threads/eventLoop eventLoop}, {@fun/Threads/Threads/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop eventLoop
```id()```函数的返回值为```threadId```。
number
id()
```javascript
function main() {
var t1 = threading.Thread(function() {
threading.currentThread().setData("data", 100)
})
Log(`t1.id():`, t1.id())
t1.join()
}
実行する文字列を作って,それを主文字列に出力します.threadId
。
{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Threads/setData set}, {@fun/Threads/Threads/Thread/name name}, {@fun/Threads/Threads/Thread/eventLoop eventLoop}, {@fun/Threads/Thread/eventLoop eventLoop}, {@fun/Threads/Thread/eventLoop eventLoop}, {@fun/Threads/thread/eventLoop eventLoop}, {@fun/Threads/thread/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop}, {@fun/
```name()```函数返回值为并发的线程名称。
string
name()
```javascript
function main() {
var t1 = threading.Thread(function() {
threading.currentThread().setData("data", 100)
})
Log(`t1.name():`, t1.name()) // t1.name(): Thread-1
t1.join()
}
連続実行するスレッドを作成し,メインスレッドに同行スレッドの名前を出力します.
{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Threads/setData set}, {@fun/Threads/Thread/id id}, {@fun/Threads/Threads/Thread/thread/eventLoop eventLoop}, {@fun/Threads/Thread/eventLoop eventLoop}, {@fun/Threads/Thread/eventLoop eventLoop}, {@fun/Threads/thread/eventLoop eventLoop}, {@fun/Threads/thread/eventLoop eventLoop}, {@fun/Threads/eventLoop eventLoop}, {@fun/Th
```eventLoop()```函数返回当前线程收到的事件信息,查看[事件信息结构](https://www.fmz.com/syntax-guide/struct/otherstruct/eventloop-return)。
object、空值
eventLoop()
eventLoop(timeout)
参数```timeout```为超时设置,单位为毫秒。参数```timeout```如果设置为0则等待有事件发生才返回,如果大于0就是设置事件等待超时,小于0立即返回最近事件。
timeout
false
number
```javascript
function main() {
var t1 = threading.Thread(function() {
while (true) {
var eventMsg = threading.currentThread().eventLoop() // 阻塞等待
// 2024-11-14 10:14:18 thread1 eventMsg: {"Seq":1,"Event":"thread","ThreadId":0,"Index":1,"Queue":0,"Nano":1731550458699947000}
Log(_D(), "thread1 eventMsg:", eventMsg)
}
})
var t2 = threading.Thread(function() {
while (true) {
var eventMsg = threading.currentThread().eventLoop(-1) // 立即返回
Log(_D(), "thread2 eventMsg:", eventMsg)
Sleep(5000)
}
})
var t3 = threading.Thread(function() {
while (true) {
var eventMsg = threading.currentThread().eventLoop(3000) // 设置3秒超时
Log(_D(), "thread3 eventMsg:", eventMsg)
}
})
t1.postMessage("Hello ", t1.name())
t2.postMessage("Hello ", t2.name())
t3.postMessage("Hello ", t3.name())
t1.join()
t2.join()
t3.join()
}
3つのスレッドを同時に実行し,受信したイベント情報を出力し,遅刻または即帰時に空値を出力します.
{@fun/Threads/Thread/peekMessage peekMessage}, {@fun/Threads/Thread/postMessage postMessage}, {@fun/Threads/Thread/join join}, {@fun/Threads/Thread/terminate terminate}, {@fun/Threads/Thread/getData getData}, {@fun/Threads/Thread/setData setData}, {@fun/Threads/Thread/id id}, {@fun/Threads/Thread/name name}
### ThreadLock
线程锁对象,用于多线程同步处理。
### acquire
```acquire()```函数用于请求一个线程锁(加锁)。
acquire()
范例可以参考```threading.Lock()```章节的内容。
```acquire()```函数用于请求一个线程锁。当一个线程调用某个线程锁对象的```acquire()```函数时,它会尝试获取锁,如果锁当前没有被其它线程占用,调用线程就会成功获得锁并继续执行。如果锁已经被其它线程持有,调用```acquire()```的线程会被阻塞,直到锁被释放。
{@fun/Threads/threading/Lock Lock}, {@fun/Threads/ThreadLock/release release}
### release
```release()```函数用于释放一个线程锁(解锁)。
release()
```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()
}
テスト死鎖シーン
線鎖の不正使用は死鎖を引き起こす可能性があることを注意してください.
{@fun/Threads/threading/Lock Lock}, {@fun/Threads/ThreadLock/acquire acquire} ローックロック
イベントオブジェクト,マルチスレッドのイベント通知,シグナル.
set()
可以参考```threading.Event()```章节范例。
如果已经```set()```设置过,不能重复设置,需要清空之后重新设置信号。
{@fun/Threads/ThreadEvent/clear clear}, {@fun/Threads/ThreadEvent/wait wait}, {@fun/Threads/ThreadEvent/isSet isSet}
### clear
```clear()```函数用于清理信号。
clear()
可以参考```threading.Event()```章节范例。
{@fun/Threads/ThreadEvent/set set}, {@fun/Threads/ThreadEvent/wait wait}, {@fun/Threads/ThreadEvent/isSet isSet}
### wait
```wait()```函数用于设置事件(信号)等待,在事件(信号)被设置之前会阻塞;支持设置超时参数。
```wait()```函数返回是否超时,如果超时返回真值。
bool
wait()
wait(timeout)
参数```timeout```用于设置等待超时,单位毫秒。
timeout
false
number
```javascript
function main() {
var event = threading.Event()
var t1 = threading.Thread(function(event) {
var ret = event.wait(100)
Log(`event.wait(100):`, ret)
ret = event.wait()
Log(`event.wait():`, ret)
}, event)
Sleep(1000)
event.set()
t1.join()
}
テストwait()
この関数の返した値は,
{@fun/Threads/ThreadEvent/set set}, {@fun/Threads/ThreadEvent/clear clear}, {@fun/Threads/ThreadEvent/isSet isSet}, {@fun/Threads/ThreadEvent/isSet isSet}, {@fun/Threads/ThreadEvent/isSet isSet}, {@fun/Threads/ThreadEvent/isSet isSet}, {@fun/Threads/ThreadEvent/isSet isSet}, {@fun/Threads/Threads/ThreadEvent/clear clear}, {@fun/Threads/Threads/Threads/isSet isSet}, {@fun/Threads/Threads/Threads/isSet isSet}, {@fun/Threads/Threads/Threads/threads/threads/threads/threads/threads/threads/threads/threads/threads/threads/threads
```isSet()```函数返回是否已经设置了事件(信号);如果当前已经设置过事件(信号)则返回真值。
bool
isSet()
可以参考```threading.Event()```章节范例。
{@fun/Threads/ThreadEvent/set set}, {@fun/Threads/ThreadEvent/clear clear}, {@fun/Threads/ThreadEvent/wait wait}
### ThreadCondition
条件对象,用于多线程同步。
### notify
```notify()```函数用于唤醒一个正在等待的线程(如果有的话)。只有调用了```wait()```方法的线程才会被唤醒。
notify()
```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)
}
}
使用するnotify()
待機中のスレッドを呼び起こします.
```notify()```函数唤醒一个线程时,这个线程会重新获取线程锁。
{@fun/Threads/ThreadCondition/notifyAll notifyAll}, {@fun/Threads/ThreadCondition/wait wait}, {@fun/Threads/ThreadCondition/acquire acquire}, {@fun/Threads/ThreadCondition/release release}
### notifyAll
```notifyAll()```函数会唤醒所有正在等待的线程。
notifyAll()
范例可以参考```ThreadCondition.notify()```章节的内容。
```notifyAll()```函数逐个唤醒所有等待中的线程,被唤醒的线程重新获取线程锁。
{@fun/Threads/ThreadCondition/notify notify}, {@fun/Threads/ThreadCondition/wait wait}, {@fun/Threads/ThreadCondition/acquire acquire}, {@fun/Threads/ThreadCondition/release release}
### wait
```wait()```函数用于在某些设计的条件下让线程等待。
wait()
范例可以参考```ThreadCondition.notify()```章节的内容。
```wait()```函数会释放线程锁,当被唤醒时重新获取线程锁。
{@fun/Threads/ThreadCondition/notify notify}, {@fun/Threads/ThreadCondition/notifyAll notifyAll}, {@fun/Threads/ThreadCondition/acquire acquire}, {@fun/Threads/ThreadCondition/release release}
### acquire
```acquire()```函数用于请求一个线程锁(加锁)。
acquire()
范例可以参考```ThreadCondition.notify()```章节的内容。
在使用```wait()```之前需要请求当前条件对象的线程锁(加锁)。
{@fun/Threads/ThreadCondition/notify notify}, {@fun/Threads/ThreadCondition/notifyAll notifyAll}, {@fun/Threads/ThreadCondition/wait wait}, {@fun/Threads/ThreadCondition/release release}
### release
```release()```函数用于释放一个线程锁(解锁)。
release()
范例可以参考```ThreadCondition.notify()```章节的内容。
在使用```wait()```之后需要释放当前条件对象的线程锁(解锁)。
{@fun/Threads/ThreadCondition/notify notify}, {@fun/Threads/ThreadCondition/notifyAll notifyAll}, {@fun/Threads/ThreadCondition/wait wait}, {@fun/Threads/ThreadCondition/acquire acquire}
### ThreadDict
字典对象,用于数据共享。
### get
```get()```函数用于获取字典对象中记录的键值。
```get()```函数返回通过参数```key```指定的键值。
string、number、bool、object、array、空值等系统支持的所有类型
get(key)
参数```key```用于指定要获取的键对应的键名。
key
true
string
```javascript
function main() {
var event = threading.Event()
var dict = threading.Dict()
dict.set("data", 100)
var t1 = threading.Thread(function(dict, event) {
Log(`thread1, dict.get("data"):`, dict.get("data"))
event.set()
event.clear()
event.wait()
Log(`after main change data, thread1 dict.get("data"):`, dict.get("data"))
dict.set("data", 0)
}, dict, event)
event.wait()
dict.set("data", 99)
event.set()
event.clear()
t1.join()
Log(`main thread, dict.get("data"):`, dict.get("data"))
}
イベントオブジェクト通知スレッドを使用してデータを読み,変更します.
{@fun/Threads/ThreadDict/セットセット}
set(key, value)
参数```key```用于设置需要修改的键名。
key
true
string
参数```value```用于设置需要修改的键值。
value
true
string、number、bool、object、array、function、空值等系统支持的所有类型
```javascript
function main() {
var dict1 = threading.Dict()
dict1.set("func1", function(p) {
Log("func1 p:", p)
})
threading.Thread(function(dict1) {
var func1 = dict1.get("func1")
func1("test")
}, dict1).join()
}
キー値伝達関数もサポートします.
{@fun/Threads/ThreadDict/get get} 楽しいこと
ネットワーク設定 ウェブ3