blob: 264b5a5d82b7cbff2971fa20f553383c0ed91a5c [file] [log] [blame] [view]
Andrew Gerrand5bc444d2014-12-10 11:35:11 +11001# Introduction
2
elagergren-spideroakbc434572018-09-06 16:03:56 -07003Some librariesespecially graphical frameworks and libraries like Cocoa, OpenGL, and libSDLuse thread-local state and can require functions to be called only from a specific OS thread, typically the 'main' thread. Go provides the `runtime.LockOSThread` function for this, but it's notoriously difficult to use correctly.
Andrew Gerrand5bc444d2014-12-10 11:35:11 +11004
5# Solutions
6
7Russ Cox presented a good solution for this problem in this [thread](https://groups.google.com/d/msg/golang-nuts/IiWZ2hUuLDA/SNKYYZBelsYJ).
8
Dmitri Shuralyov47f767a2015-01-04 21:07:59 -08009```Go
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110010package sdl
11
12// Arrange that main.main runs on main thread.
13func init() {
Dave Day0d6986a2014-12-10 15:02:18 +110014 runtime.LockOSThread()
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110015}
16
17// Main runs the main SDL service loop.
18// The binary's main.main must call sdl.Main() to run this loop.
19// Main does not return. If the binary needs to do other work, it
20// must do it in separate goroutines.
21func Main() {
Jeremy Jackins18049022015-01-27 22:24:43 +090022 for f := range mainfunc {
Dave Day0d6986a2014-12-10 15:02:18 +110023 f()
24 }
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110025}
26
27// queue of work to run in main thread.
28var mainfunc = make(chan func())
29
30// do runs f on the main thread.
31func do(f func()) {
Dave Day0d6986a2014-12-10 15:02:18 +110032 done := make(chan bool, 1)
33 mainfunc <- func() {
34 f()
35 done <- true
36 }
37 <-done
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110038}
39```
40
41And then other functions you write in package sdl can be like
Dmitri Shuralyov47f767a2015-01-04 21:07:59 -080042
43```Go
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110044func Beep() {
Dave Day0d6986a2014-12-10 15:02:18 +110045 do(func() {
46 // whatever must run in main thread
47 })
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110048}
49```