thread: Use standard context.Context

This commit is contained in:
Hajime Hoshi 2019-06-08 01:43:07 +09:00
parent 1e93d9c699
commit 449679665b
2 changed files with 16 additions and 15 deletions

View File

@ -15,6 +15,7 @@
package thread
import (
"context"
"sync/atomic"
)
@ -36,17 +37,17 @@ func New() *Thread {
// Loop starts the thread loop.
//
// Loop must be called on the thread.
func (t *Thread) Loop(ch <-chan error) error {
func (t *Thread) Loop(context context.Context) {
atomic.StoreInt32(&t.started, 1)
defer atomic.StoreInt32(&t.started, 0)
loop:
for {
select {
case f := <-t.funcs:
f()
case err := <-ch:
// ch returns a value not only when an error occur but also it is closed.
return err
case <-context.Done():
break loop
}
}
}

View File

@ -20,6 +20,7 @@
package glfw
import (
"context"
"image"
"math"
"runtime"
@ -171,11 +172,9 @@ func getCachedMonitor(wx, wy int) (*cachedMonitor, bool) {
return nil, false
}
func (u *UserInterface) mainThreadLoop(ch <-chan error) error {
func (u *UserInterface) mainThreadLoop(context context.Context) error {
u.setRunning(true)
if err := u.t.Loop(ch); err != nil {
return err
}
u.t.Loop(context)
u.setRunning(false)
return nil
}
@ -561,22 +560,23 @@ func init() {
runtime.LockOSThread()
}
func (u *UserInterface) Run(width, height int, scale float64, title string, context driver.UIContext, graphics driver.Graphics) error {
func (u *UserInterface) Run(width, height int, scale float64, title string, uicontext driver.UIContext, graphics driver.Graphics) error {
// Initialize the main thread first so the thread is available at u.run (#809).
u.t = thread.New()
ch := make(chan error)
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan error, 1)
go func() {
defer cancel()
defer close(ch)
if err := u.run(width, height, scale, title, context, graphics); err != nil {
if err := u.run(width, height, scale, title, uicontext, graphics); err != nil {
ch <- err
}
}()
if err := u.mainThreadLoop(ch); err != nil {
return err
}
return nil
u.mainThreadLoop(ctx)
return <-ch
}
func (u *UserInterface) RunWithoutMainLoop(width, height int, scale float64, title string, context driver.UIContext, graphics driver.Graphics) <-chan error {