(摘) Godot的多线程

声明:内容源自网络,版权归原作者所有。若有侵权请在网页聊天中联系我

Godot需要学习的几个点:网络、线程、着色器

线程安全的API

官方文档

使用多线程

官方文档

创建线程

var thread: Thread
func _read():
    thread = Thread.new()
    thread.start(_thread_func.bind("Waff"))

func _thread_func(user):
    print("我是一个线程,用户是:",user)

func _exit_tree():
    thread.wait_to_finish()

Mutex

当从不同线程访问一个数据时, 一定要使用 Mutex
Mutex.lock() 当其它线程试图锁同一个mutex时,就会阻塞,进入暂停状态;
Mutex.unlock() 允许其它线程锁定

var counter := 0
var mutex: Mutex
var thread: Thread

func _ready():
     mutex = Mutex.new()
     thead = Thread.new()
     thread.start(_thread_func)

     mutex.lock()
     counter += 1
     mutex.unlock()

func _thread_func():
     mutex.lock()
     counter += 1
     mutex.unlock()

func _exit_tree():
     thread.wait_to_finish()
     print("总数:",counter)

Semaphore

信号量Semaphore可以让线程按需工作。(告诉什么时候工作,什么时候暂停)
线程中使用Semaphore.wait()暂停,主线程用Semaphore.post()表示数据已准备好

var counter := 0
var mutex: Mutex
var sema: Semaphore
var thread: Thread
var exit_thread := false

func _ready():
     mutex = Mutex.new()
     sema = Semaphore.new()
     exit_thread = false

     thread = Thread.new()
     thread.start(_thread_func)

func _thread_func():
     while true:
         sema.wait()
         mutex.lock()
         var should_exit = exit_thread  # 退出线程的标识
         mutex.unlock()

         if should_exit: 
            break
         
         mutex.lock()
         counter += 1
         mutex.unlock()

func get_counter():
     mutex.lock()
     var counter_value = counter
     mutex.unlock()
     return counter_value

func _exit_tree()
     mutex.lock()
     exit_thread = true
     mutex.unlock()
     
     sema.post()

     thread.wait_to_finish()
     print("计数器:",counter)

相关文章