From 449679665b828c80480d16c96e600007a5f7b0bf Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Sat, 8 Jun 2019 01:43:07 +0900 Subject: [PATCH] thread: Use standard context.Context --- internal/thread/thread.go | 9 +++++---- internal/uidriver/glfw/ui.go | 22 +++++++++++----------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/internal/thread/thread.go b/internal/thread/thread.go index edc9ca466..c93e518f7 100644 --- a/internal/thread/thread.go +++ b/internal/thread/thread.go @@ -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 } } } diff --git a/internal/uidriver/glfw/ui.go b/internal/uidriver/glfw/ui.go index 7d44b407c..91fe7fc19 100644 --- a/internal/uidriver/glfw/ui.go +++ b/internal/uidriver/glfw/ui.go @@ -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 {