gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/pool/swap-pool_test.go (about)

     1  package pool
     2  
     3  import (
     4  	"gitee.com/sy_183/go-common/chans"
     5  	"math/rand"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func pop[X any](s *[]X) (x X, ok bool) {
    11  	if len(*s) == 0 {
    12  		return
    13  	}
    14  	x = (*s)[len(*s)-1]
    15  	*s = (*s)[:len(*s)-1]
    16  	return x, true
    17  }
    18  
    19  func TestSwapPool(t *testing.T) {
    20  	var ips = make(chan *int, 1024)
    21  	sp := NewSwapPool(100, func(p Pool[*int]) *int {
    22  		time.Sleep(time.Duration(rand.Intn(20)) * time.Millisecond)
    23  		ip := new(int)
    24  		//fmt.Printf("make new int pointer %p\n", ip)
    25  		return ip
    26  	})
    27  
    28  	go func() {
    29  		for {
    30  			ip := sp.Get()
    31  			//fmt.Printf("get int pointer %p\n", ip)
    32  			chans.TryPush(ips, ip)
    33  			time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
    34  		}
    35  	}()
    36  
    37  	go func() {
    38  		for {
    39  			select {
    40  			case ip := <-ips:
    41  				sp.Put(ip)
    42  				//default:
    43  			}
    44  			//time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
    45  		}
    46  	}()
    47  
    48  	time.Sleep(time.Hour)
    49  }