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 的一部分。