图像您有一个结构,该结构表示一次只有一个用户可以访问的资源。可能看起来像这样:
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 的资源
将其标记为 InUse 并将 *Resouce 返回到调用上下文/goroutine
我会锁定以避免任何系统级锁定(flock)并在 Go 中完成这一切
还需要有一个功能来标记资源不再使用
现在,当我遍历整个切片时,我在管理器中使用互斥锁来锁定访问。这是安全的,但我希望能够通过同时搜索已使用的资源并处理两个尝试将同一资源标记为 InUse 的 goroutine 来加快速度。
我特别想知道是否将 ResourceInUse
字段设置为 anint64
然后 usingatomic.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")
}
任何可以更好地测试这一点的单元测试也将不胜感激。
梦里花落0921
千万里不及你
相关分类