1- // Copyright 2020 The golang.design Initiative Authors.
1+ // Copyright 2021 The golang.design Initiative Authors.
22// All rights reserved. Use of this source code is governed
3- // by a GNU GPLv3 license that can be found in the LICENSE file.
3+ // by a MIT license that can be found in the LICENSE file.
4+ //
5+ // Written by Changkun Ou <changkun.de>
6+
7+ //go:build linux
8+ // +build linux
49
510package mainthread_test
611
712import (
13+ "context"
814 "fmt"
915 "os"
1016 "sync"
1117 "sync/atomic"
1218 "testing"
19+ "time"
1320
1421 "golang.design/x/mainthread"
1522 "golang.org/x/sys/unix"
@@ -22,11 +29,12 @@ func init() {
2229}
2330
2431func TestMain (m * testing.M ) {
25- mainthread .Init (func () {
26- os .Exit (m .Run ())
27- })
32+ mainthread .Init (func () { os .Exit (m .Run ()) })
2833}
2934
35+ // TestMainThread is not designed to be executed on the main thread.
36+ // This test tests the a call from this function that is invoked by
37+ // mainthread.Call is either executed on the main thread or not.
3038func TestMainThread (t * testing.T ) {
3139 var (
3240 nummain uint64
@@ -39,11 +47,14 @@ func TestMainThread(t *testing.T) {
3947 go func () {
4048 defer wg .Done ()
4149 mainthread .Call (func () {
50+ // Code inside this function is expecting to be executed
51+ // on the mainthread, this means the thread id should be
52+ // euqal to the initial process id.
4253 tid := unix .Gettid ()
4354 if tid == initTid {
4455 return
4556 }
46- t .Logf ("call is not executed on the main thread, want %d, got %d" , initTid , tid )
57+ t .Errorf ("call is not executed on the main thread, want %d, got %d" , initTid , tid )
4758 })
4859 }()
4960 go func () {
@@ -60,6 +71,29 @@ func TestMainThread(t *testing.T) {
6071 }
6172}
6273
74+ func TestGo (t * testing.T ) {
75+ done := make (chan struct {})
76+ mainthread .Go (func () {
77+ time .Sleep (time .Second )
78+ done <- struct {}{}
79+ })
80+ ctx , cancel := context .WithTimeout (context .Background (), time .Millisecond )
81+ defer cancel ()
82+ select {
83+ case <- ctx .Done ():
84+ case <- done :
85+ t .Fatalf ("mainthread.Go is not executing in parallel" )
86+ }
87+
88+ ctxx , cancell := context .WithTimeout (context .Background (), time .Second )
89+ defer cancell ()
90+ select {
91+ case <- ctxx .Done ():
92+ t .Fatalf ("mainthread.Go never schedules the function" )
93+ case <- done :
94+ }
95+ }
96+
6397func BenchmarkCall (b * testing.B ) {
6498 f := func () {}
6599 mainthread .Init (func () {
0 commit comments