github.com/cloudwego/kitex@v0.9.0/internal/wpool/pool_test.go (about) 1 /* 2 * Copyright 2021 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package wpool 18 19 import ( 20 "runtime" 21 "sync" 22 "sync/atomic" 23 "testing" 24 "time" 25 26 "github.com/cloudwego/kitex/internal/test" 27 ) 28 29 func TestWPool(t *testing.T) { 30 maxIdle := 1 31 maxIdleTime := time.Millisecond * 500 32 p := New(maxIdle, maxIdleTime) 33 var ( 34 sum int32 35 wg sync.WaitGroup 36 size int32 = 100 37 ) 38 test.Assert(t, p.Size() == 0) 39 for i := int32(0); i < size; i++ { 40 wg.Add(1) 41 p.Go(func() { 42 defer wg.Done() 43 atomic.AddInt32(&sum, 1) 44 }) 45 } 46 test.Assert(t, p.Size() != 0) 47 48 wg.Wait() 49 test.Assert(t, atomic.LoadInt32(&sum) == size) 50 for p.Size() != int32(maxIdle) { // waiting for workers finished and idle workers left 51 runtime.Gosched() 52 } 53 for p.Size() > 0 { // waiting for idle workers timeout 54 time.Sleep(maxIdleTime) 55 } 56 test.Assert(t, p.Size() == 0) 57 }