github.com/cloudwego/kitex@v0.9.0/pkg/utils/counter_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 utils
    18  
    19  import (
    20  	"sync"
    21  	"testing"
    22  
    23  	"github.com/cloudwego/kitex/internal/test"
    24  )
    25  
    26  func TestAtomicInt_Inc(t *testing.T) {
    27  	t.Parallel()
    28  
    29  	val := AtomicInt(0)
    30  	var wg sync.WaitGroup
    31  	for i := 0; i < 100; i++ {
    32  		wg.Add(1)
    33  		go func() {
    34  			val.Inc()
    35  			wg.Done()
    36  		}()
    37  	}
    38  	wg.Wait()
    39  	test.Assert(t, val == 100)
    40  }
    41  
    42  func TestAtomicInt_Dec(t *testing.T) {
    43  	t.Parallel()
    44  
    45  	val := AtomicInt(100)
    46  	var wg sync.WaitGroup
    47  	for i := 0; i < 100; i++ {
    48  		wg.Add(1)
    49  		go func() {
    50  			defer wg.Done()
    51  			val.Dec()
    52  		}()
    53  	}
    54  	wg.Wait()
    55  	test.Assert(t, val == 0)
    56  }
    57  
    58  func TestAtomicInt_Value(t *testing.T) {
    59  	t.Parallel()
    60  
    61  	val := AtomicInt(100)
    62  	var wg sync.WaitGroup
    63  	for i := 0; i < 100; i++ {
    64  		wg.Add(1)
    65  		go func() {
    66  			defer wg.Done()
    67  			v := val.Value()
    68  			test.Assert(t, v == 100)
    69  		}()
    70  	}
    71  	wg.Wait()
    72  }