Senior
type Sem interface { Lock() error TryLock() bool Release() Cap() int FreeSpace() int }
sobes.tech AI
Answer from AI
The Sem interface describes a semaphore with methods for locking and resource management:
Lock() error— locks the semaphore, waiting for resource release. Returns an error if locking is impossible.TryLock() bool— attempts to immediately acquire the semaphore, returnstrueif successful, otherwisefalse.Release()— releases the acquired resource.Cap() int— returns the maximum number of resources (semaphore capacity).FreeSpace() int— returns the number of free resources at the moment.
Example implementation of a simple semaphore using channels:
package main
import (
"fmt"
"sync"
)
type Sem interface {
Lock() error
TryLock() bool
Release()
Cap() int
FreeSpace() int
}
type semaphore struct {
ch chan struct{}
mutex sync.Mutex
}
func NewSemaphore(capacity int) Sem {
return &semaphore{ch: make(chan struct{}, capacity)}
}
func (s *semaphore) Lock() error {
s.ch <- struct{}{} // blocks if channel is full
return nil
}
func (s *semaphore) TryLock() bool {
select {
case s.ch <- struct{}{}:
return true
default:
return false
}
}
func (s *semaphore) Release() {
<-s.ch
}
func (s *semaphore) Cap() int {
return cap(s.ch)
}
func (s *semaphore) FreeSpace() int {
return cap(s.ch) - len(s.ch)
}
func main() {
sem := NewSemaphore(3)
fmt.Println("Capacity:", sem.Cap())
fmt.Println("Free space:", sem.FreeSpace())
sem.Lock()
fmt.Println("Free space after Lock:", sem.FreeSpace())
if sem.TryLock() {
fmt.Println("TryLock succeeded")
}
sem.Release()
fmt.Println("Free space after Release:", sem.FreeSpace())
}