在 Go 中使用特定值来实现锁定
来源:stackoverflow
时间:2024-03-14 11:36:26 499浏览 收藏
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《在 Go 中使用特定值来实现锁定》,聊聊,希望可以帮助到正在努力赚钱的你。
在回答另一个问题时,我使用 sync.map 编写了一个小结构来缓存 api 请求。
type postmanager struct {
sync.map
}
func (pc postmanager) fetch(id int) post {
post, ok := pc.load(id)
if ok {
fmt.printf("using cached post %v\n", id)
return post.(post)
}
fmt.printf("fetching post %v\n", id)
post = pc.fetchpost(id)
pc.store(id, post)
return post.(post)
}
不幸的是,如果两个 goroutine 同时获取同一个未缓存的 post,则两者都会发出请求。
var postManager PostManager
wg.Add(3)
var firstPost Post
var secondPost Post
var secondPostAgain Post
go func() {
// Fetches and caches 1
firstPost = postManager.Fetch(1)
defer wg.Done()
}()
go func() {
// Fetches and caches 2
secondPost = postManager.Fetch(2)
defer wg.Done()
}()
go func() {
// Also fetches and caches 2
secondPostAgain = postManager.Fetch(2)
defer wg.Done()
}()
wg.Wait()
我需要确保当同时提取相同 id 时,只允许一个人实际发出请求。另一个必须等待并将使用缓存的 post。但也不应锁定不同 id 的获取。
在上面的示例中,我希望只有一个对 pc.fetchpost(1) 和 pc.fetchpost(2) 的调用,并且它们应该是同时的。
完整代码链接。
解决方案
golang.org/x/sync/singleflight package 正是为此目的而编写的。
请注意,所有缓存访问都应该发生在传递给 do 的回调函数内。在您在评论中链接到的代码中,您可以在外部进行查找;这在某种程度上违背了目的。
此外,您必须使用指向 singleflight.group 的指针。这就是您的数据竞赛的来源,go vet 指出了这一点:
./foo.go:41:10:fetchpost 按值传递锁:command-line-arguments.postmanager 包含 golang.org/x/sync/singleflight.group 包含sync.mutex
这是我的写法(演示中的完整示例:https://play.golang.org/p/2hE721uA88S):
import (
"strconv"
"sync"
"golang.org/x/sync/singleflight"
)
type postmanager struct {
sf *singleflight.group
cache *sync.map
}
func (pc *postmanager) fetch(id int) post {
x, _, _ := pc.sf.do(strconv.itoa(id), func() (interface{}, error) {
post, ok := pc.cache.load(id)
if !ok {
post = pc.fetchpost(id)
pc.cache.store(id, post)
}
return post, nil
})
return x.(post)
}如果提取已经在进行中,看起来可以使用第二个地图来等待。
type postmanager struct {
sync.map
q sync.map
}
func (pc *postmanager) fetch(id int) post {
post, ok := pc.load(id)
if ok {
fmt.printf("using cached post %v\n", id)
return post.(post)
}
fmt.printf("fetching post %v\n", id)
if c, loaded := pc.q.loadorstore(id, make(chan struct{})); !loaded {
post = pc.fetchpost(id)
pc.store(id, post)
close(c.(chan struct{}))
} else {
<-c.(chan struct{})
post,_ = pc.load(id)
}
return post.(post)
}
或者,更复杂一点,使用相同的地图;-)
func (pc *PostManager) Fetch(id int) Post {
p, ok := pc.Load(id)
if !ok {
fmt.Printf("Fetching post %v\n", id)
if p, ok = pc.LoadOrStore(id, make(chan struct{})); !ok {
fetched = pc.fetchPost(id)
pc.Store(id, fetched)
close(p.(chan struct{}))
return fetched
}
}
if cached, ok := p.(Post); ok {
fmt.Printf("Using cached post %v\n", id)
return cached
}
fmt.Printf("Wating for cached post %v\n", id)
<-p.(chan struct{})
return pc.Fetch(id)
}以上就是《在 Go 中使用特定值来实现锁定》的详细内容,更多关于的资料请关注golang学习网公众号!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习