github.com/gogf/gf@v1.16.9/.example/os/gcache/getorset_func_lock.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/gogf/gf/os/gcache"
     6  	"github.com/gogf/gf/os/gctx"
     7  	"time"
     8  )
     9  
    10  func main() {
    11  	var (
    12  		ch    = make(chan struct{}, 0)
    13  		ctx   = gctx.New()
    14  		key   = `key`
    15  		value = `value`
    16  	)
    17  	for i := 0; i < 10; i++ {
    18  		go func(index int) {
    19  			<-ch
    20  			_, _ = gcache.Ctx(ctx).GetOrSetFuncLock(key, func() (interface{}, error) {
    21  				fmt.Println(index, "entered")
    22  				return value, nil
    23  			}, 0)
    24  		}(i)
    25  	}
    26  	close(ch)
    27  	time.Sleep(time.Second)
    28  }