From 455793869670131dd38eb3fb71eabb2dc66e302a Mon Sep 17 00:00:00 2001 From: zcy <290198252@qq.com> Date: Mon, 2 Aug 2021 00:35:40 +0800 Subject: [PATCH] add test --- test/goroutine_test.go | 112 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 test/goroutine_test.go diff --git a/test/goroutine_test.go b/test/goroutine_test.go new file mode 100644 index 0000000..a43b554 --- /dev/null +++ b/test/goroutine_test.go @@ -0,0 +1,112 @@ +/* + * @Author: your name + * @Date: 2021-08-02 00:02:17 + * @LastEditTime: 2021-08-02 00:32:36 + * @LastEditors: Please set LastEditors + * @Description: In User Settings Edit + * @FilePath: \background\test\goroutine_test.go + */ +package test + +import ( + "context" + "sync" + "testing" + "time" +) + + +func TestWaitGroup(t *testing.T) { + var wg sync.WaitGroup + wg.Add(2) + + go func () { + time.Sleep(3*time.Second) + t.Logf("job 1 done") + wg.Done() + }() + go func () { + time.Sleep(2 * time.Second) + t.Logf("job 2 done") + wg.Done() + }() + wg.Wait() + + t.Log("all finish") + + +} + +func TestChanel(t *testing.T){ + exit := make(chan bool) + go func () { + for { + select { + case <-exit: + t.Logf("exit 1") + return + case <- time.After(1 * time.Second) : + t.Logf("time out ") + } + } + }() + go func () { + for { + select { + case <-exit: + t.Logf("exit 2") + return + case <- time.After(1 * time.Second) : + t.Logf("time out ") + } + } + }() + time.Sleep(5 * time.Second) + exit <- true + t.Logf("finish") + + +} + +func TestContext(t *testing.T){ + ctx,cancel := context.WithCancel(context.Background()) + + go func () { + for { + select { + case <-ctx.Done(): + t.Logf("exit") + return + case <- time.After(1 * time.Second) : + t.Logf("time out ") + } + } + }() + + go func () { + for { + select { + case <-ctx.Done(): + t.Logf("exit") + return + case <- time.After(1 * time.Second) : + t.Logf("time out ") + } + } + }() + + go func () { + for { + select { + case <-ctx.Done(): + t.Logf("exit") + return + case <- time.After(1 * time.Second) : + t.Logf("time out ") + } + } + }() + time.Sleep(5 * time.Second) + cancel() + t.Logf("finish") +} \ No newline at end of file