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