50 lines
933 B
Go
50 lines
933 B
Go
package channels
|
|
|
|
import "runtime"
|
|
|
|
// Inspired by the go-sdl setup for allowing goroutines to coexist with a library that is single-threaded.
|
|
|
|
var (
|
|
// RayLib thread channel
|
|
RL = threadChannel{}
|
|
)
|
|
|
|
func init() {
|
|
runtime.LockOSThread()
|
|
}
|
|
|
|
// threadChannels allow you to guarantee that the given functions
|
|
// are all called sequentially to support a single-threaded library
|
|
// while still being able to use goroutines. Any function passed to
|
|
// Do() will be added to the call queue and run in order.
|
|
type threadChannel struct {
|
|
callQueue chan func()
|
|
mainFunc func(f func())
|
|
}
|
|
|
|
func (t *threadChannel) Main(main func()) {
|
|
t.callQueue = make(chan func())
|
|
|
|
t.mainFunc = func(f func()) {
|
|
done := make(chan bool, 1)
|
|
t.callQueue <- func() {
|
|
f()
|
|
done <- true
|
|
}
|
|
<-done
|
|
}
|
|
|
|
go func() {
|
|
main()
|
|
close(t.callQueue)
|
|
}()
|
|
|
|
for f := range t.callQueue {
|
|
f()
|
|
}
|
|
}
|
|
|
|
func (t *threadChannel) Do(f func()) {
|
|
t.mainFunc(f)
|
|
}
|