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)
	}
}
相关推荐
golang学习记5 小时前
Go slog 日志打印最佳实践指南
开发语言·后端·golang
水淹萌龙13 小时前
玩转 Go 表达式引擎:expr 实战指南
开发语言·后端·golang
Yeats_Liao14 小时前
Go Web 编程快速入门 07.4 - 模板(4):组合模板与逻辑控制
开发语言·后端·golang
nexttake18 小时前
5.go-zero集成gorm 和 go-redis
开发语言·后端·golang
QX_hao1 天前
【Go】--闭包
开发语言·golang
脚踏实地的大梦想家1 天前
【Go】P8 Go 语言核心数据结构:深入解析切片 (Slice)
开发语言·数据结构·golang
Tony Bai1 天前
【Go 网络编程全解】13 从 HTTP/1.1 到 gRPC:Web API 与微服务的演进
开发语言·网络·http·微服务·golang
weixin_420947641 天前
golang使用泛型
golang·1024程序员节
小画家~1 天前
第二十七:使用 Logrus + Lumberjack 创建日志中间件
golang
Yeats_Liao2 天前
Go Web 编程快速入门 05 - 表单处理:urlencoded 与 multipart
前端·golang·iphone