github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/perf/gopool/gopool_test.go (about)

     1  // Copyright 2021 ByteDance Inc.
     2  // Copyright 2023 Shawn Wang <jxskiss@126.com>.
     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  package gopool
    17  
    18  import (
    19  	"context"
    20  	"sync"
    21  	"testing"
    22  	"time"
    23  )
    24  
    25  func TestDefaultPool(t *testing.T) {
    26  	var mu sync.Mutex
    27  	var x int
    28  	var ch = make(chan struct{}, 10)
    29  	Go(func() {
    30  		mu.Lock()
    31  		x++
    32  		mu.Unlock()
    33  		ch <- struct{}{}
    34  	})
    35  
    36  	var adhocWorkerCnt int32
    37  	CtxGo(context.Background(), func() {
    38  		adhocWorkerCnt = Default().AdhocWorkerCount()
    39  
    40  		mu.Lock()
    41  		x++
    42  		mu.Unlock()
    43  		ch <- struct{}{}
    44  	})
    45  
    46  	for i := 0; i < 2; i++ {
    47  		<-ch
    48  	}
    49  	if adhocWorkerCnt == 0 {
    50  		t.Errorf("adhocWorkerCnt == 0")
    51  	}
    52  	time.Sleep(100 * time.Millisecond)
    53  	if n := Default().AdhocWorkerCount(); n != 0 {
    54  		t.Errorf("defualtPool adhoc worker count, want 0, got %d", n)
    55  	}
    56  }
    57  
    58  var registerTestPoolOnce sync.Once
    59  
    60  func TestRegister(t *testing.T) {
    61  	p := NewPool(&Config{Name: "testPool"})
    62  
    63  	// Use sync.Once to avoid error when run with argument -count=N where N > 1.
    64  	registerTestPoolOnce.Do(func() {
    65  		err := Register(p)
    66  		if err != nil {
    67  			t.Error(err)
    68  		}
    69  	})
    70  
    71  	p = Get("testPool")
    72  	if p == nil {
    73  		t.Error("Get did not return registered pool")
    74  	}
    75  }