A distributed barrier synchronizer for Go
RedisBarrier A distributed synchronization barrier implementation using Redis. This library provides a way to synchronize multiple processes or goroutines across different machines using Redis as the coordination mechanism (the barrier).
Inspired by cyclicbarrier https://github.com/marusama/cyclicbarrier
go get github.com/igarashi-G/redisbarrier
import (
"context"
"time"
"github.com/go-redis/redis/v8"
"github.com/igarashi-G/redisbarrier"
)
// Create Redis client
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
// Create a barrier that requires 3 parties
barrier := redisbarrier.NewRedisBarrier(rdb, "my_barrier", 3, 30*time.Second)
// Wait at the barrier
ctx := context.Background()
err := barrier.Await(ctx)
if err != nil {
// Handle error
}
// Create a barrier with an action
barrier := redisbarrier.NewRedisBarrierWithAction(
rdb,
"action_barrier",
2,
30*time.Second,
func() error {
// This will be executed by the last party to arrive
return nil
},
)
// Wait at the barrier
err := barrier.Await(ctx)
// Get the number of parties currently waiting
waiting := barrier.GetNumberWaiting()
// Get the total number of parties required
parties := barrier.GetParties()
// Check if the barrier is broken
isBroken := barrier.IsBroken()
// Reset the barrier state
barrier.Reset()
- Make sure Redis server is running on localhost:6379
- Run the tests:
go test -v ./...
Check the examples
directory for complete usage examples:
cd examples
go run main.go
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.