当前位置: 首页 > news >正文

go 开发小技巧

一、简介

       本篇文章会介绍go 开发小技巧。

二、go 开发技巧

2.1 Semaphore
type Semaphore chan struct{}func NewSemaphore(maxCount int) Semaphore {return make(chan struct{}, maxCount)
}func (s Semaphore) Acquire() {s <- struct{}{}
}func (s Semaphore) Release() {<-s
}
2.2 singleflight

    有点类似react的useMemo hook,会缓存函数结果


type SingleFlight struct {m map[string]*call
}type call struct {sync.Onceres any
}func newSingleFlight() *SingleFlight {return &SingleFlight{m: make(map[string]*call),}
}func (sf *SingleFlight) Do(key string, fn func() (any, error)) (any, error) {if sf.m[key] != nil {return sf.m[key].res, nil}ca := &call{}var err errorca.Once.Do(func() {if res, e := fn(); e == nil {ca.res = reserr = esf.m[key] = ca}})return ca.res, err
}
demo
func main() {var sf = newSingleFlight()var wg sync.WaitGroupvar t = time.Now()for i := 0; i < 10; i++ {wg.Add(1)go func() {res, _ := sf.Do("longFunc", func() (any, error) {time.Sleep(5 * time.Second)return 5, nil})fmt.Println(res)wg.Done()}()}wg.Wait()fmt.Println(time.Since(t))
}


http://www.mrgr.cn/news/13457.html

相关文章:

  • 论文速递 | Operations Research 7月文章合集
  • 开发新系统时,数据库字符集怎么选择对中文的支持最好?
  • 浏览器多开,让WhatsApp多账号管理更高效
  • kotlin协程之 协程概念的具像化
  • 使用推测解码提高 LLM 推理速度
  • 47-java节点流和处理流
  • 利用Python对Excel数据进行条件筛选与排序
  • EmguCV学习笔记 VB.Net 6.4 霍夫变换
  • 第3章 ECMAScript 7 新特性
  • 【习题】ArkUI进阶
  • 算法设计:实验二贪心算法
  • SQL的瑞士军刀:COALESCE与NULLIF的巧用
  • PHP教育培训企业小程序多端平台系统源码
  • Objective-C 中的管道艺术:NSPipe 通信全解析
  • 计算机的错误计算(七十六)
  • HikariPool-1 - Exception during pool initialization报错解决
  • 为什么需要对即将上线的系统进行压力测试
  • 常见的算法底层思想
  • 深入解析:Nginx 中会话持久性问题的解决策略
  • 279.完全平方数