登录
首页 >  Golang >  Go问答

如何实现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学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>