gitee.com/quant1x/gox@v1.21.2/coroutine/periodic_once_test.go (about)

     1  package coroutine
     2  
     3  import (
     4  	"fmt"
     5  	"gitee.com/quant1x/gox/concurrent"
     6  	"strconv"
     7  	"testing"
     8  	"time"
     9  )
    10  
    11  var (
    12  	once PeriodicOnce
    13  	//cache = map[string]int{}
    14  	//cache = cmap.NewStringMap[int]()
    15  	cache = concurrent.NewHashMap[string, int]()
    16  )
    17  
    18  func lazyInit() {
    19  	for i := 0; i < 5; i++ {
    20  		k := strconv.Itoa(i)
    21  		//cache[k] = i
    22  		cache.Set(k, i)
    23  		fmt.Println("reset", k, "=>", i)
    24  	}
    25  }
    26  
    27  func getInt(key string) (int, bool) {
    28  	once.Do(lazyInit)
    29  	//v, ok := cache[key]
    30  	v, ok := cache.Get(key)
    31  	return v, ok
    32  }
    33  func setInt(key string, value int) {
    34  	once.Do(lazyInit)
    35  	//cache[key] = value
    36  	cache.Set(key, value)
    37  }
    38  
    39  func TestPeriodicOnce(t *testing.T) {
    40  	rwCount := 1000
    41  	producer := func() {
    42  		for i := 0; i < rwCount; i++ {
    43  			k := strconv.Itoa(i % 5)
    44  			setInt(k, i)
    45  			fmt.Println(k, "=>", i)
    46  			time.Sleep(time.Millisecond * 10)
    47  		}
    48  	}
    49  	reader := func() {
    50  		for i := 0; i < rwCount; i++ {
    51  			k := strconv.Itoa(i % 5)
    52  			v, ok := getInt(k)
    53  			fmt.Println(v, "<=", i, ":", ok)
    54  			_ = v
    55  			_ = ok
    56  			time.Sleep(time.Millisecond * 10)
    57  		}
    58  	}
    59  
    60  	go producer()
    61  	go reader()
    62  	count := 60
    63  	for i := 0; i < count; i++ {
    64  		//once.Reset()
    65  		fmt.Println("--------------------")
    66  		time.Sleep(time.Second)
    67  	}
    68  }