CyclicBarrier golang implementation

Overview

cyclicbarrier

Awesome Build Status Go Report Card Coverage Status GoDoc License

CyclicBarrier is a synchronizer that allows a set of goroutines to wait for each other to reach a common execution point, also called a barrier.

Inspired by Java CyclicBarrier https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CyclicBarrier.html and C# Barrier https://msdn.microsoft.com/en-us/library/system.threading.barrier(v=vs.110).aspx

Usage

Initiate

import "github.com/marusama/cyclicbarrier"
...
b1 := cyclicbarrier.New(10) // new cyclic barrier with parties = 10
...
b2 := cyclicbarrier.NewWithAction(10, func() error { return nil }) // new cyclic barrier with parties = 10 and with defined barrier action

Await

b.Await(ctx)    // await other parties

Reset

b.Reset()       // reset the barrier

Simple example

// create a barrier for 10 parties with an action that increments counter
// this action will be called each time when all goroutines reach the barrier
cnt := 0
b := cyclicbarrier.NewWithAction(10, func() error {
    cnt++
    return nil
})

wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {           // create 10 goroutines (the same count as barrier parties)
    wg.Add(1)
    go func() {
        for j := 0; j < 5; j++ {
            
            // do some hard work 5 times
            time.Sleep(100 * time.Millisecond)                     
            
            err := b.Await(context.TODO()) // ..and wait for other parties on the barrier.
                                           // Last arrived goroutine will do the barrier action
                                           // and then pass all other goroutines to the next round
            if err != nil {
                panic(err)
            }
        }
        wg.Done()
    }()
}

wg.Wait()
fmt.Println(cnt)                    // cnt = 5, it means that the barrier was passed 5 times

For more documentation see https://godoc.org/github.com/marusama/cyclicbarrier

Issues
  • why ErrBrokenBarrier is nil value?

    why ErrBrokenBarrier is nil value?

    var (
    	// ErrBrokenBarrier error used when a goroutine tries to wait upon a barrier that is in a broken state,
    	// or which enters the broken state while the goroutine is waiting.
    	ErrBrokenBarrier error
    )
    
    bug good first issue 
    opened by raintean 1
  • Why Reset method of Barrier interface is needed?

    Why Reset method of Barrier interface is needed?

    Barrier Class (System.Threading) | Microsoft Docs do not have Reset method.

    and

    CyclicBarrier (Java SE 9 & JDK 9 ) say

    reset public void reset​() Resets the barrier to its initial state. If any parties are currently waiting at the barrier, they will return with a BrokenBarrierException. Note that resets after a breakage has occurred for other reasons can be complicated to carry out; threads need to re-synchronize in some other way, and choose one to perform the reset. It may be preferable to instead create a new barrier for subsequent use.

    So I think we don't need the Reset method.

    wontfix 
    opened by aQuaYi 1
  • Some Bug

    Some Bug

    I copy the source code to local

    and add some code betweenL135-L137 like below

    log.Println(count)
    time.Sleep(time.Duration(2) * time.Second)
    

    image

    I found that count will be greater than parties, and then panic

    package main
    
    import (
    	"context"
    	"sync"
    
    	"example.com/m/cyclicbarrier"
    )
    
    func main() {
    	barrier := cyclicbarrier.New(2)
    	wg := &sync.WaitGroup{}
    
    	wg.Add(1)
    	go func() {
    		barrier.Await(context.Background())
    		wg.Done()
    	}()
    
    	wg.Add(1)
    	go func() {
    		barrier.Await(context.Background())
    		wg.Done()
    	}()
    
    	wg.Add(1)
    	go func() {
    		barrier.Await(context.Background())
    		wg.Done()
    	}()
    
    	wg.Wait()
    }
    

    image

    opened by CoderIvan 0
Releases(v1.1.0)
Owner
Bator Tsyrendylykov
Bator Tsyrendylykov
Golang Implementation of Worker Pool/ Thread Pool

Golang Implementation of Worker Pool/ Thread Pool

Telkom DEV 1 Jun 18, 2022
🚦 Semaphore pattern implementation with timeout of lock/unlock operations.

?? semaphore Semaphore pattern implementation with timeout of lock/unlock operations. ?? Idea The semaphore provides API to control access to a shared

Kamil Samigullin 89 May 11, 2022
A cross goroutine storage tool with very simple implementation and function.

Simple-goroutine-local is a cross goroutine storage tool with very simple implementation and function (the concept is similar to Java ThreadLocal). Ge

null 0 Jan 13, 2022
Simple in-memory job queue for Golang using worker-based dispatching

artifex Simple in-memory job queue for Golang using worker-based dispatching Documentation here: https://godoc.org/github.com/mborders/artifex Cron jo

Matthew Borders 134 Jun 16, 2022
TryLock support on read-write lock for Golang

go-trylock TryLock support on read-write lock for Golang Interface go-trylock implements sync.Locker. Have same interfaces with sync.RWMutex Documenta

Guoqiang Chen 28 Mar 24, 2022
golang worker pool , Concurrency limiting goroutine pool

golang worker pool 中文说明 Concurrency limiting goroutine pool. Limits the concurrency of task execution, not the number of tasks queued. Never blocks su

xxj 398 Jun 21, 2022
Fast resizable golang semaphore primitive

semaphore Fast resizable golang semaphore based on CAS allows weighted acquire/release; supports cancellation via context; allows change semaphore lim

Bator Tsyrendylykov 146 Jun 29, 2022
Off heap golang memory pool

Stealthpool stealthpool provides a memory pool that allocates blocks off-heap that will NOT be tracked by the garbage collector. The name stealthpool

null 55 Jun 10, 2022
Queue is a Golang library for spawning and managing a Goroutine pool

Queue is a Golang library for spawning and managing a Goroutine pool, Alloowing you to create multiple worker according to limit CPU number of machine.

Bo-Yi Wu 189 Jun 26, 2022
Queue is a Golang library for spawning and managing a Goroutine pool

Queue is a Golang library for spawning and managing a Goroutine pool, Alloowing you to create multiple worker according to limit CPU number of machine.

golang-queue 190 Jun 28, 2022
This repository collects common concurrency patterns in Golang

Go Concurrency Patterns This repository collects common concurrency patterns in Golang Materials Concurrency is not parallelism Go Concurrency Pattern

Kha Nguyen 1.7k Jun 23, 2022
goroutine pool in golang

goroutine pool in golang

wksw 1 Nov 1, 2021
Routine - ThreadLocal for golang

routine 中文版 routine encapsulates and provides some easy-to-use, high-performance

Tim 35 Jun 17, 2022
Goworkers - Zero dependency Golang worker pool

Golang Worker Pool Zero dependency golang goroutines pool library. It is useful

Madhav Bhargava 0 Apr 28, 2022
Go-miningcore-pool - Miningcore Pool written in GOlang

Go-Miningcore-Pool (COMING SOON) Miningcore Pool written in GOlang 0x01 Configur

miningcore.com 2 Apr 24, 2022
Worker - A Golang library that provides worker pools

Worker A Golang library that provides worker pools. Usage See *_test.go files. T

Fatih Cetinkaya 2 Apr 15, 2022
Go language implementation of a blockchain based on the BDLS BFT protocol. The implementation was adapted from Ethereum and Sperax implementation

BDLS protocol based PoS Blockchain Most functionalities of this client is similar to the Ethereum golang implementation. If you do not find your quest

Yongge Wang 0 Jan 1, 2022
CVE-2021-4034 - A Golang implementation of clubby789's implementation of CVE-2021-4034

CVE-2021-4034 January 25, 2022 | An00bRektn This is a golang implementation of C

Ryan S. 10 Feb 3, 2022
graylog-golang is a full implementation for sending messages in GELF (Graylog Extended Log Format) from Go (Golang) to Graylog

graylog-golang is a full implementation for sending messages in GELF (Graylog Extended Log Format) from Go (Golang) to Graylog

Robert Kowalski 77 May 25, 2022
goRBAC provides a lightweight role-based access control (RBAC) implementation in Golang.

goRBAC goRBAC provides a lightweight role-based access control implementation in Golang. For the purposes of this package: * an identity has one or mo

Xing 1.3k Jun 26, 2022
This is an implementation of JWT in golang!

jwt This is a minimal implementation of JWT designed with simplicity in mind. What is JWT? Jwt is a signed JSON object used for claims based authentic

John Rowley 99 May 9, 2022
Golang implementation of JSON Web Tokens (JWT)

jwt-go A go (or 'golang' for search engine friendliness) implementation of JSON Web Tokens NEW VERSION COMING: There have been a lot of improvements s

Dave Grijalva 10.4k Jul 4, 2022
Platform-Agnostic Security Tokens implementation in GO (Golang)

Golang implementation of PASETO: Platform-Agnostic Security Tokens This is a 100% compatible pure Go (Golang) implementation of PASETO tokens. PASETO

Oleg Lobanov 608 Jun 26, 2022
OAuth 1.0 implementation in go (golang).

OAuth 1.0 Library for Go (If you need an OAuth 2.0 library, check out: https://godoc.org/golang.org/x/oauth2) Developing your own apps, with this libr

Matt Jones 258 Jun 16, 2022
A golang implementation of a console-based trading bot for cryptocurrency exchanges

Golang Crypto Trading Bot A golang implementation of a console-based trading bot for cryptocurrency exchanges. Usage Download a release or directly bu

Alessandro Sanino 794 Jun 27, 2022
A simple Set data structure implementation in Go (Golang) using LinkedHashMap.

Set Set is a simple Set data structure implementation in Go (Golang) using LinkedHashMap. This library allow you to get a set of int64 or string witho

Studio Sol Comunicação Digital Ltda 21 Apr 6, 2022
Golang implementation of Radix trees

go-radix Provides the radix package that implements a radix tree. The package only provides a single Tree implementation, optimized for sparse nodes.

Armon Dadgar 734 Jun 19, 2022
HyperLogLog and HyperLogLog++ implementation in Go/Golang.

HyperLogLog and HyperLogLog++ Implements the HyperLogLog and HyperLogLog++ algorithms. HyperLogLog paper: http://algo.inria.fr/flajolet/Publications/F

Clark DuVall 408 Jun 24, 2022
Golang implementation of the Raft consensus protocol

raft raft is a Go library that manages a replicated log and can be used with an FSM to manage replicated state machines. It is a library for providing

HashiCorp 6.2k Jun 29, 2022