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 小时前
Go error 处理:errors.Is/As 与错误包装
开发语言·后端·golang·go·错误处理
灯澜忆梦3 小时前
Go 工程管理与作用域
golang
进击的程序猿~12 小时前
Go Zero源码阅读1
后端·golang
李燚19 小时前
Go 项目怎么组织:DDD 4 层 vs MVC vs 脚本式
开发语言·golang·mvc·ddd·agent框架·eino
Generalzy1 天前
从 Web 页面到桌面应用:用 Go + WebView 构建一个轻量级桌面框架
开发语言·前端·golang
灯澜忆梦1 天前
GO_函数_2
开发语言·golang·xcode
灯澜忆梦1 天前
Go 语言圣经 5 | 函数全解:声明、签名、闭包、Defer、Panic 错误处理
数据结构·算法·golang
进击的程序猿~1 天前
Go Zero源码阅读2
开发语言·后端·golang
zenithdev12 天前
fastcache:为 Go 设计的低 GC 压力内存缓存
开发语言·其他·缓存·golang
北冥you鱼2 天前
Go语言sync包在区块链开发中的数据同步实践
golang·centos·区块链