如何实现Go并发map或slice来更快地管理正在使用的资源?
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《如何实现Go并发map或slice来更快地管理正在使用的资源?》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!
想象一下,你有一个结构体,代表一次只有一个用户可以访问的资源。可能看起来像这样:
type resource struct{
inuse bool//or int32/int64 is you want to use atomics
resource string //parameters that map to the resource, think `/dev/chardevicexxx`
}
这些资源的数量是有限的,用户将随机且并发地请求访问它们,因此您将它们打包在管理器中
type resourcemanager struct{
resources []*resource //or a map
}
我正在尝试找出管理器创建函数 func (m *resourcemanager)getunusedresouce()(*resouce,error) 的最佳、安全方法,该函数将:
- 迭代所有资源,直到找到未使用的资源
- 将其标记为 inuse 并将 *resouce 返回到调用上下文/goroutine
- 我会锁定以避免任何系统级锁定(flock),并在 go 中完成这一切
- 还需要有一个函数来标记资源不再使用
现在,当我迭代整个切片时,我在管理器中使用互斥锁来锁定访问。它是安全的,但我希望通过能够同时搜索已使用的资源并处理两个试图将同一资源标记为 inuse 的 goroutine 来加快速度。
更新
我特别想知道是否将资源 inuse 字段设置为 int64 然后使用 atomic.compareandswapint64 将允许资源管理器在发现未使用的资源时正确锁定:
func (m *ResourceManager)GetUnusedResouce()(*Resouce,error){
for i := range Resources{
if atomic.CompareAndSwapInt64(&Resouces[i].InUse,1){
return Resouces[i],nil
}
}
return nil, errors.New("all resouces in use")
}
任何可以更好地测试这一点的单元测试也将不胜感激。
正确答案
问题中的 getunusedresouce 函数可能会对所有资源执行比较和交换操作。根据资源数量和应用程序访问模式,执行受互斥锁保护的少量操作可能会更快。
使用单链表实现快速的get和put操作。
type resource struct {
next *resource
resource string
}
type resourcemanager struct {
free *resource
mu sync.mutex
}
// get gets a free resource from the manager or returns
// nil when the manager is empty.
func (m *resourcemanager) get() *resource {
m.mu.lock()
defer m.mu.unlock()
result := m.free
if m.free != nil {
m.free = m.free.next
}
return result
}
// put returns a resource to the pool.
func (m *resourcemanager) put(r *resource) {
m.mu.lock()
defer m.mu.unlock()
r.next = m.free
m.free = r
}
以下是测试中的使用示例:
func testresourcemanager(t *testing.t) {
// add free resources to a manager.
var m resourcemanager
m.put(&resource{resource: "/dev/a"})
m.put(&resource{resource: "/dev/b"})
// test that we can get all resources from the pool.
ra := m.get()
rb := m.get()
if ra.resource > rb.resource {
// sort ra, rb to make test independent of order.
ra, rb = rb, ra
}
if ra == nil || ra.resource != "/dev/a" {
t.errorf("ra is %v, want /dev/a", ra)
}
if rb == nil || rb.resource != "/dev/b" {
t.errorf("rb is %v, want /dev/b", rb)
}
// check for empty pool.
r := m.get()
if r != nil {
t.errorf("r is %v, want nil", r)
}
// return one resource and try again.
m.put(ra)
ra = m.get()
if ra == nil || ra.resource != "/dev/a" {
t.errorf("ra is %v, want /dev/a", ra)
}
r = m.get()
if r != nil {
t.errorf("r is %v, want nil", r)
}
}
Run the test on the playground。
如果资源数量存在已知的合理限制,请使用通道。此方法利用了运行时高度优化的通道实现。
type resource struct {
resource string
}
type resourcemanager struct {
free chan *resource
}
// get gets a free resource from the manager or returns
// nil when the manager is empty.
func (m *resourcemanager) get() *resource {
select {
case r := <-m.free:
return r
default:
return nil
}
}
// put returns a resource to the pool.
func (m *resourcemanager) put(r *resource) {
m.free <- r
}
// newresourcemanager returns a manager that can hold up to
// n free resources.
func newresourcemanager(n int) *resourcemanager {
return &resourcemanager{free: make(chan *resource, n)}
}
使用上面的 testresourcemanager 函数测试此实现,但将 var m resourcemanager 替换为 m := newresourcemanager(4)。
Run the test on the Go playground。
给定资源是否正在使用不是 resource 本身的属性,而是 resourcemanager 的属性。
事实上,没有必要跟踪正在使用的资源(除非由于问题中未提及的某种原因需要跟踪)。正在使用的资源在释放时可以简单地放回池中。
这是使用通道的可能实现。不需要一个互斥锁,也不需要任何原子 cas。
package main
import (
fmt "fmt"
"time"
)
type Resource struct {
Data string
}
type ResourceManager struct {
resources []*Resource
closeCh chan struct{}
acquireCh chan *Resource
releaseCh chan *Resource
}
func NewResourceManager() *ResourceManager {
r := &ResourceManager{
closeCh: make(chan struct{}),
acquireCh: make(chan *Resource),
releaseCh: make(chan *Resource),
}
go r.run()
return r
}
func (r *ResourceManager) run() {
defer close(r.acquireCh)
for {
if len(r.resources) > 0 {
select {
case r.acquireCh <- r.resources[len(r.resources)-1]:
r.resources = r.resources[:len(r.resources)-1]
case res := <-r.releaseCh:
r.resources = append(r.resources, res)
case <-r.closeCh:
return
}
} else {
select {
case res := <-r.releaseCh:
r.resources = append(r.resources, res)
case <-r.closeCh:
return
}
}
}
}
func (r *ResourceManager) AcquireResource() *Resource {
return <-r.acquireCh
}
func (r *ResourceManager) ReleaseResource(res *Resource) {
r.releaseCh <- res
}
func (r *ResourceManager) Close() {
close(r.closeCh)
}
// small demo below ...
func test(id int, r *ResourceManager) {
for {
res := r.AcquireResource()
fmt.Printf("test %d: %s\n", id, res.Data)
time.Sleep(time.Millisecond)
r.ReleaseResource(res)
}
}
func main() {
r := NewResourceManager()
r.ReleaseResource(&Resource{"Resource A"}) // initial setup
r.ReleaseResource(&Resource{"Resource B"}) // initial setup
go test(1, r)
go test(2, r)
go test(3, r) // 3 consumers, but only 2 resources ...
time.Sleep(time.Second)
r.Close()
}理论要掌握,实操不能落!以上关于《如何实现Go并发map或slice来更快地管理正在使用的资源?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
如何在 Go 中解码 JSON,它以类型数组的形式返回多个元素,以类型的形式返回单个元素
- 上一篇
- 如何在 Go 中解码 JSON,它以类型数组的形式返回多个元素,以类型的形式返回单个元素
- 下一篇
- 交通运输部:3 月份共收到网约车订单信息 8.91 亿单,环比上升 15%
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 478浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3166次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3378次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3407次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4511次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3787次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览

