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)
	}
}
相关推荐
lars_lhuan2 小时前
Go WaitGroup 源码解析
golang
人间打气筒(Ada)7 小时前
如何基于 Go-kit 开发 Web 应用:从接口层到业务层再到数据层
开发语言·后端·golang
想搞艺术的程序员12 小时前
Go RWMutex 源码分析:一个计数器,如何把“读多写少”做得又快又稳
开发语言·redis·golang
喵了几个咪13 小时前
GoWind Content Hub|风行,开箱即用的企业级前后端一体内容中台
vue.js·golang·react·taro
人间打气筒(Ada)14 小时前
go实战案例:如何基于 Conul 给微服务添加服务注册与发现?
开发语言·微服务·zookeeper·golang·kubernetes·etcd·consul
superantwmhsxx14 小时前
[golang][MAC]Go环境搭建+VsCode配置
vscode·macos·golang
Cocktail_py15 小时前
Windows直接部署crawlab
windows·python·golang
人间打气筒(Ada)16 小时前
go实战案例:如何在 Go-kit 和 Service Meh 中进行服务注册与发现?
开发语言·后端·golang·istio·go-kit
小白的代码日记16 小时前
区块链分叉检测与回扫系统(Go语言)
人工智能·golang·区块链
brucelee18616 小时前
Windows 11 安装 Go(Golang)教程
开发语言·windows·golang