github.com/whtcorpsinc/milevadb-prod@v0.0.0-20211104133533-f57f4be3b597/soliton/localpool/localpool_test.go (about)

     1  // Copyright 2020 WHTCORPS INC, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  // +build !race
    15  
    16  package localpool
    17  
    18  import (
    19  	"math/rand"
    20  	"runtime"
    21  	"sync"
    22  	"testing"
    23  
    24  	. "github.com/whtcorpsinc/check"
    25  )
    26  
    27  type Obj struct {
    28  	val int64
    29  }
    30  
    31  func TestT(t *testing.T) {
    32  	TestingT(t)
    33  }
    34  
    35  var _ = Suite(&testPoolSuite{})
    36  
    37  type testPoolSuite struct {
    38  }
    39  
    40  func (s *testPoolSuite) TestPool(c *C) {
    41  	numWorkers := runtime.GOMAXPROCS(0)
    42  	wg := new(sync.WaitGroup)
    43  	wg.Add(numWorkers)
    44  	pool := NewLocalPool(16, func() interface{} {
    45  		return new(Obj)
    46  	}, nil)
    47  	n := 1000
    48  	for i := 0; i < numWorkers; i++ {
    49  		go func() {
    50  			for j := 0; j < n; j++ {
    51  				GetAndPut(pool)
    52  			}
    53  			wg.Done()
    54  		}()
    55  	}
    56  	wg.Wait()
    57  	var getHit, getMiss, putHit, putMiss int
    58  	for _, slot := range pool.slots {
    59  		getHit += slot.getHit
    60  		getMiss += slot.getMiss
    61  		putHit += slot.putHit
    62  		putMiss += slot.putMiss
    63  	}
    64  	c.Assert(getHit, Greater, getMiss)
    65  	c.Assert(putHit, Greater, putMiss)
    66  }
    67  
    68  func GetAndPut(pool *LocalPool) {
    69  	objs := make([]interface{}, rand.Intn(4)+1)
    70  	for i := 0; i < len(objs); i++ {
    71  		objs[i] = pool.Get()
    72  	}
    73  	runtime.Gosched()
    74  	for _, obj := range objs {
    75  		pool.Put(obj)
    76  	}
    77  }