├── go.mod ├── go.sum ├── .gitignore ├── .github └── workflows │ └── mainthread.yml ├── bench_test.go ├── example_test.go ├── LICENSE ├── mainthread_test.go ├── README.md └── mainthread.go /go.mod: -------------------------------------------------------------------------------- 1 | module golang.design/x/mainthread 2 | 3 | go 1.16 4 | 5 | require golang.org/x/sys v0.0.0-20201022201747-fb209a7c41cd 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | golang.org/x/sys v0.0.0-20201022201747-fb209a7c41cd h1:WgqgiQvkiZWz7XLhphjt2GI2GcGCTIZs9jqXMWmH+oc= 2 | golang.org/x/sys v0.0.0-20201022201747-fb209a7c41cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | -------------------------------------------------------------------------------- /.github/workflows/mainthread.yml: -------------------------------------------------------------------------------- 1 | name: mainthread 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | name: Build 12 | runs-on: ubuntu-latest 13 | steps: 14 | 15 | - uses: actions/checkout@v2 16 | - uses: actions/setup-go@v2 17 | with: 18 | stable: 'false' 19 | go-version: '1.16.0' 20 | 21 | - name: Test 22 | run: | 23 | go test -v -covermode=atomic ./... 24 | -------------------------------------------------------------------------------- /bench_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020-2021 The golang.design Initiative Authors. 2 | // All rights reserved. Use of this source code is governed 3 | // by a MIT license that can be found in the LICENSE file. 4 | // 5 | // Written by Changkun Ou 6 | 7 | package mainthread_test 8 | 9 | import ( 10 | "testing" 11 | 12 | "golang.design/x/mainthread" 13 | ) 14 | 15 | func BenchmarkCall(b *testing.B) { 16 | f := func() {} 17 | mainthread.Init(func() { 18 | b.ReportAllocs() 19 | b.ResetTimer() 20 | for i := 0; i < b.N; i++ { 21 | mainthread.Call(f) 22 | } 23 | }) 24 | } 25 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020-2021 The golang.design Initiative Authors. 2 | // All rights reserved. Use of this source code is governed 3 | // by a MIT license that can be found in the LICENSE file. 4 | // 5 | // Written by Changkun Ou 6 | 7 | package mainthread_test 8 | 9 | import ( 10 | "fmt" 11 | 12 | "golang.design/x/mainthread" 13 | ) 14 | 15 | func ExampleInit() { 16 | mainthread.Init(func() { 17 | // ... Do stuff ... 18 | }) 19 | // Output: 20 | } 21 | 22 | func ExampleCall() { 23 | mainthread.Init(func() { 24 | mainthread.Call(func() { 25 | fmt.Println("from main thread") 26 | }) 27 | }) 28 | // Output: from main thread 29 | } 30 | 31 | func ExampleGo() { 32 | mainthread.Init(func() { 33 | done := make(chan string) 34 | mainthread.Go(func() { 35 | done <- "main thread" 36 | }) 37 | fmt.Println("from", <-done) 38 | }) 39 | // Output: from main thread 40 | } 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Changkun Ou 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /mainthread_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020-2021 The golang.design Initiative Authors. 2 | // All rights reserved. Use of this source code is governed 3 | // by a MIT license that can be found in the LICENSE file. 4 | // 5 | // Written by Changkun Ou 6 | 7 | //go:build linux 8 | // +build linux 9 | 10 | package mainthread_test 11 | 12 | import ( 13 | "context" 14 | "os" 15 | "sync" 16 | "sync/atomic" 17 | "testing" 18 | "time" 19 | 20 | "golang.design/x/mainthread" 21 | "golang.org/x/sys/unix" 22 | ) 23 | 24 | var initTid int 25 | 26 | func init() { 27 | initTid = unix.Getpid() 28 | } 29 | 30 | func TestMain(m *testing.M) { 31 | mainthread.Init(func() { os.Exit(m.Run()) }) 32 | } 33 | 34 | // TestMainThread is not designed to be executed on the main thread. 35 | // This test tests the a call from this function that is invoked by 36 | // mainthread.Call is either executed on the main thread or not. 37 | func TestMainThread(t *testing.T) { 38 | var ( 39 | nummain uint64 40 | numcall = 100000 41 | ) 42 | 43 | wg := sync.WaitGroup{} 44 | for i := 0; i < numcall; i++ { 45 | wg.Add(2) 46 | go func() { 47 | defer wg.Done() 48 | mainthread.Call(func() { 49 | // Code inside this function is expecting to be executed 50 | // on the mainthread, this means the thread id should be 51 | // euqal to the initial process id. 52 | tid := unix.Gettid() 53 | if tid == initTid { 54 | return 55 | } 56 | t.Errorf("call is not executed on the main thread, want %d, got %d", initTid, tid) 57 | }) 58 | }() 59 | go func() { 60 | defer wg.Done() 61 | if unix.Gettid() == initTid { 62 | atomic.AddUint64(&nummain, 1) 63 | } 64 | }() 65 | } 66 | wg.Wait() 67 | 68 | if nummain == uint64(numcall) { 69 | t.Fatalf("all non main thread calls are executed on the main thread.") 70 | } 71 | } 72 | 73 | func TestGo(t *testing.T) { 74 | done := make(chan struct{}) 75 | mainthread.Go(func() { 76 | time.Sleep(time.Second) 77 | done <- struct{}{} 78 | }) 79 | ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) 80 | defer cancel() 81 | select { 82 | case <-ctx.Done(): 83 | case <-done: 84 | t.Fatalf("mainthread.Go is not executing in parallel") 85 | } 86 | 87 | ctxx, cancell := context.WithTimeout(context.Background(), time.Second*2) 88 | defer cancell() 89 | select { 90 | case <-ctxx.Done(): 91 | t.Fatalf("mainthread.Go never schedules the function") 92 | case <-done: 93 | } 94 | } 95 | 96 | func TestPanickedFuncCall(t *testing.T) { 97 | defer func() { 98 | if r := recover(); r != nil { 99 | return 100 | } 101 | t.Fatalf("expected to panic, but actually not") 102 | }() 103 | 104 | mainthread.Call(func() { 105 | panic("die") 106 | }) 107 | } 108 | 109 | func TestPanickedFuncGo(t *testing.T) { 110 | defer func() { 111 | if err := mainthread.Error(); err != nil { 112 | return 113 | } 114 | t.Fatalf("expected to panic, but actually not") 115 | }() 116 | 117 | mainthread.Go(func() { panic("die") }) 118 | mainthread.Call(func() {}) // for sync 119 | } 120 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mainthread [![PkgGoDev](https://pkg.go.dev/badge/golang.design/x/mainthread)](https://pkg.go.dev/golang.design/x/mainthread) ![mainthread](https://github.com/golang-design/mainthread/workflows/mainthread/badge.svg?branch=main) ![](https://changkun.de/urlstat?mode=github&repo=golang-design/mainthread) 2 | 3 | schedule functions to run on the main thread 4 | 5 | ```go 6 | import "golang.design/x/mainthread" 7 | ``` 8 | 9 | ## Features 10 | 11 | - Main thread scheduling 12 | - Schedule functions without memory allocation 13 | 14 | ## API Usage 15 | 16 | Package mainthread offers facilities to schedule functions 17 | on the main thread. To use this package properly, one must 18 | call `mainthread.Init` from the main package. For example: 19 | 20 | ```go 21 | package main 22 | 23 | import "golang.design/x/mainthread" 24 | 25 | func main() { mainthread.Init(fn) } 26 | 27 | // fn is the actual main function 28 | func fn() { 29 | // ... do stuff ... 30 | 31 | // mainthread.Call returns when f1 returns. Note that if f1 blocks 32 | // it will also block the execution of any subsequent calls on the 33 | // main thread. 34 | mainthread.Call(f1) 35 | 36 | // ... do stuff ... 37 | 38 | 39 | // mainthread.Go returns immediately and f2 is scheduled to be 40 | // executed in the future. 41 | mainthread.Go(f2) 42 | 43 | // ... do stuff ... 44 | } 45 | 46 | func f1() { ... } 47 | func f2() { ... } 48 | ``` 49 | 50 | If the given function triggers a panic, and called via `mainthread.Call`, 51 | then the panic will be propagated to the same goroutine. One can capture 52 | that panic, when possible: 53 | 54 | ```go 55 | defer func() { 56 | if r := recover(); r != nil { 57 | println(r) 58 | } 59 | }() 60 | 61 | mainthread.Call(func() { ... }) // if panic 62 | ``` 63 | 64 | If the given function triggers a panic, and called via `mainthread.Go`, 65 | then the panic will be cached internally, until a call to the `Error()` method: 66 | 67 | ```go 68 | mainthread.Go(func() { ... }) // if panics 69 | 70 | // ... do stuff ... 71 | 72 | if err := mainthread.Error(); err != nil { // can be captured here. 73 | println(err) 74 | } 75 | ``` 76 | 77 | Note that a panic happens before `mainthread.Error()` returning the 78 | panicked error. If one needs to guarantee `mainthread.Error()` indeed 79 | captured the panic, a dummy function can be used as synchornization: 80 | 81 | ```go 82 | mainthread.Go(func() { panic("die") }) // if panics 83 | mainthread.Call(func() {}) // for execution synchronization 84 | err := mainthread.Error() // err must be non-nil 85 | ``` 86 | 87 | 88 | It is possible to cache up to a maximum of 42 panicked errors. 89 | More errors are ignored. 90 | 91 | ## When do you need this package? 92 | 93 | Read this to learn more about the design purpose of this package: 94 | https://golang.design/research/zero-alloc-call-sched/ 95 | 96 | ## Who is using this package? 97 | 98 | The initial purpose of building this package is to support writing 99 | graphical applications in Go. To know projects that are using this 100 | package, check our [wiki](https://github.com/golang-design/mainthread/wiki) 101 | page. 102 | 103 | 104 | ## License 105 | 106 | MIT | © 2021 The golang.design Initiative Authors, written by [Changkun Ou](https://changkun.de). -------------------------------------------------------------------------------- /mainthread.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020-2021 The golang.design Initiative Authors. 2 | // All rights reserved. Use of this source code is governed 3 | // by a MIT license that can be found in the LICENSE file. 4 | // 5 | // Written by Changkun Ou 6 | 7 | // Package mainthread offers facilities to schedule functions 8 | // on the main thread. To use this package properly, one must 9 | // call `mainthread.Init` from the main package. For example: 10 | // 11 | // package main 12 | // 13 | // import "golang.design/x/mainthread" 14 | // 15 | // func main() { mainthread.Init(fn) } 16 | // 17 | // // fn is the actual main function 18 | // func fn() { 19 | // // ... do stuff ... 20 | // 21 | // // mainthread.Call returns when f1 returns. Note that if f1 blocks 22 | // // it will also block the execution of any subsequent calls on the 23 | // // main thread. 24 | // mainthread.Call(f1) 25 | // 26 | // // ... do stuff ... 27 | // 28 | // 29 | // // mainthread.Go returns immediately and f2 is scheduled to be 30 | // // executed in the future. 31 | // mainthread.Go(f2) 32 | // 33 | // // ... do stuff ... 34 | // } 35 | // 36 | // func f1() { ... } 37 | // func f2() { ... } 38 | // 39 | // If the given function triggers a panic, and called via `mainthread.Call`, 40 | // then the panic will be propagated to the same goroutine. One can capture 41 | // that panic, when possible: 42 | // 43 | // defer func() { 44 | // if r := recover(); r != nil { 45 | // println(r) 46 | // } 47 | // }() 48 | // 49 | // mainthread.Call(func() { ... }) // if panic 50 | // 51 | // If the given function triggers a panic, and called via `mainthread.Go`, 52 | // then the panic will be cached internally, until a call to the `Error()` method: 53 | // 54 | // mainthread.Go(func() { ... }) // if panics 55 | // 56 | // // ... do stuff ... 57 | // 58 | // if err := mainthread.Error(); err != nil { // can be captured here. 59 | // println(err) 60 | // } 61 | // 62 | // Note that a panic happens before `mainthread.Error()` returning the 63 | // panicked error. If one needs to guarantee `mainthread.Error()` indeed 64 | // captured the panic, a dummy function can be used as synchornization: 65 | // 66 | // mainthread.Go(func() { panic("die") }) // if panics 67 | // mainthread.Call(func() {}) // for execution synchronization 68 | // err := mainthread.Error() // err must be non-nil 69 | // 70 | // It is possible to cache up to a maximum of 42 panicked errors. 71 | // More errors are ignored. 72 | package mainthread // import "golang.design/x/mainthread" 73 | 74 | import ( 75 | "fmt" 76 | "runtime" 77 | "sync" 78 | ) 79 | 80 | func init() { 81 | runtime.LockOSThread() 82 | } 83 | 84 | // Init initializes the functionality of running arbitrary subsequent 85 | // functions be called on the main system thread. 86 | // 87 | // Init must be called in the main.main function. 88 | func Init(main func()) { 89 | done := donePool.Get().(chan error) 90 | defer donePool.Put(done) 91 | 92 | go func() { 93 | defer func() { 94 | done <- nil 95 | }() 96 | main() 97 | }() 98 | 99 | for { 100 | select { 101 | case f := <-funcQ: 102 | func() { 103 | defer func() { 104 | r := recover() 105 | if f.done != nil { 106 | if r != nil { 107 | f.done <- fmt.Errorf("%v", r) 108 | } else { 109 | f.done <- nil 110 | } 111 | } else { 112 | if r != nil { 113 | select { 114 | case erroQ <- fmt.Errorf("%v", r): 115 | default: 116 | } 117 | } 118 | } 119 | }() 120 | f.fn() 121 | }() 122 | case <-done: 123 | return 124 | } 125 | } 126 | } 127 | 128 | // Call calls f on the main thread and blocks until f finishes. 129 | func Call(f func()) { 130 | done := donePool.Get().(chan error) 131 | defer donePool.Put(done) 132 | 133 | data := funcData{fn: f, done: done} 134 | funcQ <- data 135 | if err := <-done; err != nil { 136 | panic(err) 137 | } 138 | } 139 | 140 | // Go schedules f to be called on the main thread. 141 | func Go(f func()) { 142 | funcQ <- funcData{fn: f} 143 | } 144 | 145 | // Error returns an error that is captured if there are any panics 146 | // happened on the mainthread. 147 | // 148 | // It is possible to cache up to a maximum of 42 panicked errors. 149 | // More errors are ignored. 150 | func Error() error { 151 | select { 152 | case err := <-erroQ: 153 | return err 154 | default: 155 | return nil 156 | } 157 | } 158 | 159 | var ( 160 | funcQ = make(chan funcData, runtime.GOMAXPROCS(0)) 161 | erroQ = make(chan error, 42) 162 | donePool = sync.Pool{New: func() interface{} { 163 | return make(chan error) 164 | }} 165 | ) 166 | 167 | type funcData struct { 168 | fn func() 169 | done chan error 170 | } 171 | --------------------------------------------------------------------------------