如何实现Go并发map或slice来更快地管理正在使用的资源?
来源:stackoverflow
时间:2024-05-01 16:03:33 110浏览 收藏
来到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学习网公众号吧!
-
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次学习