-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.go
More file actions
94 lines (76 loc) · 2.13 KB
/
thread.go
File metadata and controls
94 lines (76 loc) · 2.13 KB
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
88
89
90
91
92
93
94
package darwin
import (
"runtime"
"sync"
"github.com/ebitengine/purego"
)
var (
goCallbackFuncs = make(map[uintptr]func())
goCallbackFuncsMtx sync.Mutex
goCallbackFuncsIndex uintptr
classGoCallback uintptr
)
func MainThread(f func()) {
// If we are already on the main thread, execute the function directly to avoid deadlock.
runtime.LockOSThread()
isMain := isMainThread()
runtime.UnlockOSThread()
if isMain {
f()
return
}
// If we are on a different goroutine, dispatch the function to the main
// thread and wait for it to complete.
var wg sync.WaitGroup
wg.Add(1)
dispatch(func() {
defer wg.Done()
f()
})
wg.Wait()
}
func isMainThread() bool {
return Objc_sendMsg[bool](Class_NSThread, Sel_isMainThread)
}
func dispatch(f func()) {
goCallbackFuncsMtx.Lock()
goCallbackFuncsIndex++
idx := goCallbackFuncsIndex
goCallbackFuncs[idx] = f
goCallbackFuncsMtx.Unlock()
cb := Objc_sendMsg[uintptr](classGoCallback, Sel_alloc)
cb = Objc_sendMsg[uintptr](cb, Sel_init)
// Wrap the primitive uintptr in an NSNumber object.
nsIdx := Objc_sendMsg[uintptr](Class_NSNumber, Sel_numberWithInt, idx)
Objc_sendMsg[uintptr](cb, Sel_performSelectorOnMainThread, Sel_call, nsIdx, 1)
// We no longer need the manual retain on 'cb'. The system handles it.
// The balancing release for 'cb' is still in goCallback.
}
func goCallback(id, sel, arg uintptr) {
// 'arg' is now an NSNumber. We need to extract the integer value.
idx := Objc_sendMsg[uintptr](arg, Sel_unsignedLongLongValue)
goCallbackFuncsMtx.Lock()
f, ok := goCallbackFuncs[idx]
if ok {
delete(goCallbackFuncs, idx)
}
goCallbackFuncsMtx.Unlock()
if ok {
f()
}
// Release the callback object now that we're done with it.
Objc_sendMsg[uintptr](id, Sel_release)
}
func setupGoCallbackClass() {
className := "GoCallback"
class := objc_allocateClassPair(Class_NSObject, className, 0)
if class == 0 {
panic("failed to allocate GoCallback class")
}
classGoCallback = class
ok := class_addMethod(class, Sel_call, purego.NewCallback(goCallback), "v@:@")
if !ok {
panic("failed to add method 'call' to GoCallback")
}
objc_registerClassPair(class)
}