From 9fd40a37b87bf8b784ee2e513df3252f69d3ae0b Mon Sep 17 00:00:00 2001 From: Sasha Koshka Date: Mon, 11 Nov 2024 11:38:59 -0500 Subject: [PATCH] sync: Don't panic on double close of Gate, return error instead --- sync/gate.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/sync/gate.go b/sync/gate.go index f55a18d..cc63d4b 100644 --- a/sync/gate.go +++ b/sync/gate.go @@ -2,6 +2,16 @@ package usync import "sync" +// Error defines errors that this package can produce +type Error string; const ( + ErrAlreadyClosed Error = "AlreadyClosed" +) + +// Error fullfills the error interface. +func (err Error) Error () string { + return string(err) +} + // Gate wraps a channel and allows the receiver to abruptly stop receiving // messages without causing the sender to lock up. type Gate[T any] struct { @@ -47,6 +57,7 @@ func (this *Gate[T]) Receive () <- chan T { // Close closes the gate, drains all remaining messages, and closes the channel. func (this *Gate[T]) Close () error { this.lock.Lock() + if !this.open { return ErrAlreadyClosed } this.open = false this.lock.Unlock() for len(this.channel) > 0 { <- this.channel }