饥饿锁

package main

import (
  "fmt"
  "sync"
)

var defaultCacheSize = 1 << 4

type Block struct {
  ch chan chan struct{}
}

func NewBlock(cache_size ...uint) *Block {
  if len(cache_size) > 0 && cache_size[0] > 0 {
  	return &Block{make(chan chan struct{}, cache_size[0])}
  }
  return &Block{
  	ch: make(chan chan struct{}, defaultCacheSize),
  }
}
func (b *Block) Release() {
  close(b.ch)
}
func (b *Block) Acquire(c chan struct{}) {
  b.ch <- c
  go func() {
  	(<-b.ch) <- struct{}{}
  }()
}

func main() {
  b := NewBlock()
  defer b.Release()
  var wg sync.WaitGroup
  defer wg.Wait()
  for i := range defaultCacheSize {
  	c := make(chan struct{})
  	wg.Add(1)
  	go func() {
  		defer wg.Done()
  		b.Acquire(c)
  		<-c
  		fmt.Printf("%d Acquired lock\n", i)
  		close(c)
  	}()
  }
}
posted @ 2025-07-25 16:41  ishmaelwanglin  阅读(5)  评论(0)    收藏  举报