-
Notifications
You must be signed in to change notification settings - Fork 4
/
mainthread_test.go
119 lines (103 loc) · 2.46 KB
/
mainthread_test.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// Copyright 2020-2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build linux
// +build linux
package mainthread_test
import (
"context"
"os"
"sync"
"sync/atomic"
"testing"
"time"
"golang.design/x/mainthread"
"golang.org/x/sys/unix"
)
var initTid int
func init() {
initTid = unix.Getpid()
}
func TestMain(m *testing.M) {
mainthread.Init(func() { os.Exit(m.Run()) })
}
// TestMainThread is not designed to be executed on the main thread.
// This test tests the a call from this function that is invoked by
// mainthread.Call is either executed on the main thread or not.
func TestMainThread(t *testing.T) {
var (
nummain uint64
numcall = 100000
)
wg := sync.WaitGroup{}
for i := 0; i < numcall; i++ {
wg.Add(2)
go func() {
defer wg.Done()
mainthread.Call(func() {
// Code inside this function is expecting to be executed
// on the mainthread, this means the thread id should be
// euqal to the initial process id.
tid := unix.Gettid()
if tid == initTid {
return
}
t.Errorf("call is not executed on the main thread, want %d, got %d", initTid, tid)
})
}()
go func() {
defer wg.Done()
if unix.Gettid() == initTid {
atomic.AddUint64(&nummain, 1)
}
}()
}
wg.Wait()
if nummain == uint64(numcall) {
t.Fatalf("all non main thread calls are executed on the main thread.")
}
}
func TestGo(t *testing.T) {
done := make(chan struct{})
mainthread.Go(func() {
time.Sleep(time.Second)
done <- struct{}{}
})
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
defer cancel()
select {
case <-ctx.Done():
case <-done:
t.Fatalf("mainthread.Go is not executing in parallel")
}
ctxx, cancell := context.WithTimeout(context.Background(), time.Second*2)
defer cancell()
select {
case <-ctxx.Done():
t.Fatalf("mainthread.Go never schedules the function")
case <-done:
}
}
func TestPanickedFuncCall(t *testing.T) {
defer func() {
if r := recover(); r != nil {
return
}
t.Fatalf("expected to panic, but actually not")
}()
mainthread.Call(func() {
panic("die")
})
}
func TestPanickedFuncGo(t *testing.T) {
defer func() {
if err := mainthread.Error(); err != nil {
return
}
t.Fatalf("expected to panic, but actually not")
}()
mainthread.Go(func() { panic("die") })
mainthread.Call(func() {}) // for sync
}