forked from HACKERALERT/mainthread
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mainthread.go
87 lines (75 loc) · 1.76 KB
/
mainthread.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package mainthread
import (
"errors"
"runtime"
)
// CallQueueCap is the capacity of the call queue. This means how many calls to CallNonBlock will not
// block until some call finishes.
//
// The default value is 16 and should be good for 99% usecases.
var CallQueueCap = 16
var (
callQueue chan func()
)
func init() {
runtime.LockOSThread()
}
func checkRun() {
if callQueue == nil {
panic(errors.New("mainthread: did not call Run"))
}
}
// Run enables mainthread package functionality. To use mainthread package, put your main function
// code into the run function (the argument to Run) and simply call Run from the real main function.
//
// Run returns when run (argument) function finishes.
func Run(run func()) {
callQueue = make(chan func(), CallQueueCap)
done := make(chan struct{})
go func() {
run()
done <- struct{}{}
}()
for {
select {
case f := <-callQueue:
f()
case <-done:
return
}
}
}
// CallNonBlock queues function f on the main thread and returns immediately. Does not wait until f
// finishes.
func CallNonBlock(f func()) {
checkRun()
callQueue <- f
}
// Call queues function f on the main thread and blocks until the function f finishes.
func Call(f func()) {
checkRun()
done := make(chan struct{})
callQueue <- func() {
f()
done <- struct{}{}
}
<-done
}
// CallErr queues function f on the main thread and returns an error returned by f.
func CallErr(f func() error) error {
checkRun()
errChan := make(chan error)
callQueue <- func() {
errChan <- f()
}
return <-errChan
}
// CallVal queues function f on the main thread and returns a value returned by f.
func CallVal(f func() interface{}) interface{} {
checkRun()
respChan := make(chan interface{})
callQueue <- func() {
respChan <- f()
}
return <-respChan
}