github.com/sandwich-go/boost@v1.3.29/xpool/goroutine_test.go (about)

     1  package xpool
     2  
     3  import (
     4  	"runtime"
     5  	"sync"
     6  	"sync/atomic"
     7  	"testing"
     8  	"time"
     9  )
    10  
    11  func init() {
    12  	runtime.GOMAXPROCS(runtime.NumCPU())
    13  }
    14  
    15  func TestNewPool(t *testing.T) {
    16  	pool := NewGoroutinePool(10, 100, time.Duration(0))
    17  	defer pool.Close()
    18  
    19  	iterations := 20
    20  	var counter uint64 = 0
    21  
    22  	wg := sync.WaitGroup{}
    23  	wg.Add(iterations)
    24  	for i := 0; i < iterations; i++ {
    25  		arg := uint64(1)
    26  		job := func() {
    27  			defer wg.Done()
    28  			time.Sleep(time.Duration(1) * time.Second)
    29  			atomic.AddUint64(&counter, arg)
    30  		}
    31  
    32  		pool.jobQueue <- job
    33  	}
    34  	wg.Wait()
    35  
    36  	counterFinal := atomic.LoadUint64(&counter)
    37  	if uint64(iterations) != counterFinal {
    38  		t.Errorf("iterations %v is not equal counterFinal %v", iterations, counterFinal)
    39  	}
    40  }