v8.run/go/exp@v0.0.26-0.20230226010534-afcdbd3f782d/pool2/gopool1/gopool1_test.go (about) 1 package gopool1_test 2 3 import ( 4 "math" 5 "sync" 6 "sync/atomic" 7 "testing" 8 "time" 9 10 "v8.run/go/exp/pool2/gopool1" 11 ) 12 13 func TestGoPool1Leak(t *testing.T) { 14 var v uint64 15 pool, err := gopool1.New( 16 math.MaxInt64, 17 func(v *uint64) { 18 atomic.AddUint64(v, 1) 19 }, 20 time.Millisecond*500, 21 time.Millisecond*100, 22 0, 23 ) 24 if err != nil { 25 panic(err) 26 } 27 defer pool.Stop() 28 29 const N = 100000 30 for i := 0; i < N; i++ { 31 ok := pool.Run(&v) 32 if !ok { 33 panic("pool is full") 34 } 35 } 36 time.Sleep(time.Second * 2) 37 38 if atomic.LoadUint64(&v) != N { 39 t.Errorf("v = %d, want %d", v, N) 40 } 41 42 if w := pool.Workers(); w != 0 { 43 t.Errorf("workers = %d, want 0, goroutine leak!!!", w) 44 } 45 } 46 47 func TestGoPool1Stop(t *testing.T) { 48 var v uint64 49 pool, err := gopool1.New( 50 math.MaxInt64, 51 func(v *uint64) { 52 atomic.AddUint64(v, 1) 53 }, 54 time.Hour, 55 time.Millisecond*100, 56 0, 57 ) 58 if err != nil { 59 panic(err) 60 } 61 62 const N = 100000 63 for i := 0; i < N; i++ { 64 ok := pool.Run(&v) 65 if !ok { 66 panic("pool is full") 67 } 68 } 69 pool.Stop() // stop the pool 70 time.Sleep(time.Second * 2) 71 72 if atomic.LoadUint64(&v) != N { 73 t.Errorf("v = %d, want %d", v, N) 74 } 75 76 if w := pool.Workers(); w != 0 { 77 t.Errorf("workers = %d, want 0, goroutine leak!!!", w) 78 } 79 } 80 81 func TestGoPool1Preheat(t *testing.T) { 82 pool, err := gopool1.New( 83 math.MaxInt64, 84 func(v *uint64) { 85 atomic.AddUint64(v, 1) 86 }, 87 time.Hour, 88 time.Millisecond*100, 89 10, 90 ) 91 if err != nil { 92 panic(err) 93 } 94 95 if w := pool.Workers(); w != 10 { 96 t.Errorf("workers = %d, want 10", w) 97 } 98 99 pool.Stop() 100 time.Sleep(time.Second * 1) 101 102 if w := pool.Workers(); w != 0 { 103 t.Errorf("workers = %d, want 0, goroutine leak!!!", w) 104 } 105 } 106 107 func testIOJob30ms(wg *sync.WaitGroup) { 108 time.Sleep(time.Millisecond * 30) 109 wg.Done() 110 } 111 112 func TestGoPool1WorkerCount(t *testing.T) { 113 pool, err := gopool1.New( 114 math.MaxInt64, 115 testIOJob30ms, 116 time.Second*30, 117 time.Minute, 118 0, 119 ) 120 var wg sync.WaitGroup 121 122 if err != nil { 123 panic(err) 124 } 125 126 if w := pool.Workers(); w != 0 { 127 t.Errorf("workers = %d, want 0", w) 128 } 129 130 wg.Add(1) 131 pool.Run(&wg) 132 wg.Wait() 133 134 if w := pool.Workers(); w != 1 { 135 t.Errorf("workers = %d, want 1", w) 136 } 137 138 wg.Add(2) 139 pool.Run(&wg) 140 pool.Run(&wg) 141 wg.Wait() 142 143 if w := pool.Workers(); w != 2 { 144 t.Errorf("workers = %d, want 2", w) 145 } 146 147 // Stop the pool 148 pool.Stop() 149 time.Sleep(time.Second * 1) 150 151 if w := pool.Workers(); w != 0 { 152 t.Errorf("workers = %d, want 0, goroutine leak!!!", w) 153 } 154 }