Go Wiki:LockOSThread

簡介

有些函式庫(特別是圖形框架和函式庫,例如 Cocoa、OpenGL 和 libSDL)使用執行緒本機狀態,而且可能需要僅從特定作業系統執行緒(通常是「主要」執行緒)呼叫函式。Go 提供了 runtime.LockOSThread 函式來執行此操作,但出了名的難以正確使用。

解決方案

Russ Cox 在此 討論串 中提出了此問題的良好解決方案。

package sdl

// Arrange that main.main runs on main thread.
func init() {
    runtime.LockOSThread()
}

// Main runs the main SDL service loop.
// The binary's main.main must call sdl.Main() to run this loop.
// Main does not return. If the binary needs to do other work, it
// must do it in separate goroutines.
func Main() {
    for f := range mainfunc {
        f()
    }
}

// queue of work to run in main thread.
var mainfunc = make(chan func())

// do runs f on the main thread.
func do(f func()) {
    done := make(chan bool, 1)
    mainfunc <- func() {
        f()
        done <- true
    }
    <-done
}

然後您在 sdl 套件中撰寫的其他函式可以像這樣

func Beep() {
    do(func() {
        // whatever must run in main thread
    })
}

此內容是 Go Wiki 的一部分。