Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
Thread
繼承: RefCounted < Object
程序中的執行單元。
說明
A unit of execution in a process. Can run methods on Objects simultaneously. The use of synchronization via Mutex or Semaphore is advised if working with shared objects.
Warning: To ensure proper cleanup without crashes or deadlocks, when a Thread's reference count reaches zero and it is therefore destroyed, the following conditions must be met:
It must not have any Mutex objects locked.
It must not be waiting on any Semaphore objects.
wait_to_finish() should have been called on it.
教學
方法
get_id() const |
|
is_alive() const |
|
is_main_thread() static |
|
is_started() const |
|
void |
set_thread_safety_checks_enabled(enabled: bool) static |
列舉
enum Priority: 🔗
Priority PRIORITY_LOW = 0
執行緒以比正常情況下更低的優先順序運作。
Priority PRIORITY_NORMAL = 1
具有標準優先順序的執行緒。
Priority PRIORITY_HIGH = 2
以比正常情況更高的優先順序運作的執行緒。
方法說明
返回目前 Thread 的 ID,能夠在所有執行緒中唯一標識該執行緒。如果該 Thread 尚未運作,或者已經呼叫過 wait_to_finish(),則返回空字串。
如果這個 Thread 目前正在運作,則返回 true。可用於確定呼叫 wait_to_finish() 是否可以不阻塞呼叫的執行緒。
要檢查 Thread 是否可被併入,請使用 is_started()。
bool is_main_thread() static 🔗
Returns true if the thread this method was called from is the main thread.
Note: This is a static method and isn't associated with a specific Thread object.
如果此 Thread 已啟動,則返回 true。一旦開始,這將返回 true ,直到它使用 wait_to_finish() 加入。要檢查 Thread 是否仍在執行其工作,請使用 is_alive()。
void set_thread_safety_checks_enabled(enabled: bool) static 🔗
設定是否應該在目前執行緒執行執行緒安全檢查,這些檢查在一般是在某些類(例如 Node)的方法中進行的。
每個執行緒的預設值是啟用(就像將 true 傳給 enabled 呼叫一樣)。
這些檢查是保守的。也就是說,只有在引擎能夠確保安全時才會認為該呼叫是執行緒安全的,檢查通過(因此允許進行呼叫)。
因此,某些情況下用於可能會想要將其禁用(讓 enabled 為 false),允許某些操作。此時引擎不再保護這些物件的執行緒安全,(通過使用 Mutex 等方法來)確保執行緒安全就是使用者自己的責任了。
注意:這是引擎的高階用法。建議只有在你知道自己在做什麼,並且沒有其他更安全的方法時才使用這個方法。
注意:可用於任意 Thread 物件中執行的腳本,或者提交至 WorkerThreadPool 的工作。Node 群組處理時執行的程式碼不適用,這種情況下會始終執行檢查。
注意:即使是在 WorkerThreadPool 工作中禁用了檢查,也不需要在結束後將其重新啟用。引擎會幫你去啟用。
Error start(callable: Callable, priority: Priority = 1) 🔗
啟動一個呼叫 callable 的新 Thread。
如果該方法需要一些參數,可以使用 Callable.bind() 傳遞它們。
Thread 的 priority 可以通過傳遞 Priority 列舉中的值來更改。
成功時返回 @GlobalScope.OK,失敗時返回 @GlobalScope.ERR_CANT_CREATE。
合併該 Thread 並等待其完成。返回傳入 start() 的 Callable 的輸出。
應該在你想要獲取該 Thread 所呼叫的方法的返回值時使用,或者在釋放包含該 Thread 的實例前使用。
要確定呼叫時是否不會阻塞呼叫執行緒,請檢查 is_alive() 是否為 false。