面试题答案
一键面试设计思路
- 资源池:使用一个通道来表示资源池,通道中的元素表示可用资源。
- 分配资源:通过
select
语句从资源池通道中接收资源,若资源池为空,select
会阻塞,直到有资源可用。 - 回收资源:当使用完资源后,将资源发送回资源池通道。
关键代码
package main
import (
"fmt"
)
// Resource 表示资源
type Resource struct {
// 这里可以定义资源相关的属性
}
// ResourceManager 资源管理器
type ResourceManager struct {
resourcePool chan *Resource
}
// NewResourceManager 创建一个新的资源管理器
func NewResourceManager(capacity int) *ResourceManager {
rm := &ResourceManager{
resourcePool: make(chan *Resource, capacity),
}
for i := 0; i < capacity; i++ {
rm.resourcePool <- &Resource{}
}
return rm
}
// Allocate 分配资源
func (rm *ResourceManager) Allocate() *Resource {
select {
case res := <-rm.resourcePool:
return res
}
}
// Release 回收资源
func (rm *ResourceManager) Release(res *Resource) {
select {
case rm.resourcePool <- res:
}
}
你可以这样使用:
func main() {
rm := NewResourceManager(5)
go func() {
res := rm.Allocate()
fmt.Println("Allocated resource:", res)
// 使用资源
rm.Release(res)
fmt.Println("Released resource:", res)
}()
// 防止main函数退出
select {}
}