Go Barrier栅栏

1. 简介

实现与pythonthreading.Barrier库类似的功能,多线程同时等待达到指定数量一起放行。

有待改进地方

  1. wait方法没有支持context控制。

2. 代码

go 复制代码
import (
	"context"
	"golang.org/x/sync/semaphore"
	"sync/atomic"
)

type Barrier struct {
	count  int64 // 记录当前多少
	amount int64 // 记录多少放行
	entry  *semaphore.Weighted
	exit   *semaphore.Weighted
}

func NewBarrier(n int64) *Barrier {
	b := &Barrier{
		count:  0,
		amount: n,
		entry:  semaphore.NewWeighted(n),
		exit:   semaphore.NewWeighted(n),
	}
	_ = b.exit.Acquire(context.Background(), n)
	return b
}

func (b *Barrier) Wait() {
	ctx := context.Background()

	// 限制进入数量
	_ = b.entry.Acquire(context.Background(), 1)

	// 如果是最后一个人,放行前面所有包括自己。
	if atomic.AddInt64(&b.count, 1) == b.amount {
		defer func() {
			b.count = 0
			b.entry.Release(b.amount)
		}()

		// 放行所有
		b.exit.Release(b.amount)
	}

	// 等待放行
	_ = b.exit.Acquire(ctx, 1)
}

测试

go 复制代码
func TestBarrier(t *testing.T) {
	b := NewBarrier(2)
	for i := 1; i <= 10; i++ {
		go func(id int) {
			b.Wait()
			t.Log("waited", id)
		}(i)
		time.Sleep(time.Second)
	}
}
相关推荐
二楼后座。1 小时前
Golang操作MySQL json字段优雅写法
mysql·golang·json
熬了夜的程序员4 小时前
【华为机试】HJ61 放苹果
算法·华为·面试·golang
亚洲第一中锋_哈达迪6 小时前
详解缓存淘汰策略:LRU
后端·缓存·golang
卜锦元20 小时前
Go中使用wire进行统一依赖注入管理
开发语言·后端·golang
mit6.8241 天前
论容器化 | 分析Go和Rust做医疗的后端服务
docker·golang·rust
ykuaile_h81 天前
Go 编译报错排查:vendor/golang.org/x/crypto/cryptobyte/asn1 no Go source files
后端·golang
Nejosi_念旧2 天前
解读 Go 中的 constraints包
后端·golang·go
风无雨2 天前
GO 启动 简单服务
开发语言·后端·golang
小明的小名叫小明2 天前
Go从入门到精通(19)-协程(goroutine)与通道(channel)
后端·golang
光影少年2 天前
从前端转go开发的学习路线
前端·学习·golang