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)
	}
}
相关推荐
我不是8神19 分钟前
go-zero微服务框架总结
开发语言·微服务·golang
遇见你的雩风5 小时前
【Golang】--- Goroutine
开发语言·golang
YGGP6 小时前
【Golang】LeetCode 189. 轮转数组
开发语言·leetcode·golang
桂花很香,旭很美7 小时前
[7天实战入门Go语言后端] Day 3:项目结构与配置——目录组织、环境变量与 viper
开发语言·数据库·golang
桂花很香,旭很美7 小时前
[7天实战入门Go语言后端] Day 4:Go 数据层入门——database/sql 与简单 CRUD
数据库·sql·golang
qinaoaini1 天前
[golang][MAC]Go环境搭建+VsCode配置
vscode·macos·golang
花酒锄作田1 天前
Go - slog使用入门
golang
u***35741 天前
对基因列表中批量的基因进行GO和KEGG注释
开发语言·数据库·golang
好家伙VCC1 天前
# 发散创新:基于 Go 语言打造高性能服务网格的实践与突破在微服务架构
java·python·微服务·架构·golang
unirst19850071 天前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang