MST

星途 面试题库

面试题:Go语言通道选择机制与并发资源管理

假设有多个goroutine并发访问共享资源,使用通道选择机制(select语句)实现一个资源管理器,要求能够安全地分配和回收资源,避免资源泄漏和竞争条件。请说明设计思路并给出关键代码。
34.4万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 资源池:使用一个通道来表示资源池,通道中的元素表示可用资源。
  2. 分配资源:通过select语句从资源池通道中接收资源,若资源池为空,select会阻塞,直到有资源可用。
  3. 回收资源:当使用完资源后,将资源发送回资源池通道。

关键代码

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 {}
}