Go Wiki: LockOSThread
はじめに
一部のライブラリ、特にCocoa、OpenGL、libSDLなどのグラフィカルフレームワークやライブラリは、スレッドローカルの状態を使用し、特定のOSスレッド(通常は「メイン」スレッド)からのみ関数を呼び出す必要があります。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の一部です。