From 967e6e68ab48785366db218e4215c5ff8624500d Mon Sep 17 00:00:00 2001 From: "Alexander I.Grafov" Date: Mon, 4 Nov 2019 22:26:49 +0300 Subject: [PATCH] Fix side effects of sink.Close() refs #4 and #5 Fixed in a straight way by removing logic with sink ID. The logic was corrupted any way. Aman Gupta explained the problem in #5 and figured out the cause with sink ID. In this change I suppose that a number of sinks will not very large. --- sink.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/sink.go b/sink.go index 7c65adf..d955642 100644 --- a/sink.go +++ b/sink.go @@ -53,7 +53,6 @@ const ( var collector struct { sync.RWMutex sinks []*Sink - count int } type ( @@ -61,7 +60,6 @@ type ( // and decides how to filter them. Each output wraps its own io.Writer. // Sink methods are safe for concurrent usage. Sink struct { - id uint In chan chain close chan struct{} writer io.Writer @@ -108,9 +106,7 @@ func SinkTo(w io.Writer, fn Formatter) *Sink { } ) collector.Lock() - sink.id = uint(collector.count) collector.sinks = append(collector.sinks, sink) - collector.count++ collector.Unlock() go processSink(sink) return sink @@ -310,8 +306,14 @@ func (s *Sink) Close() { atomic.StoreInt32(s.state, sinkClosed) s.close <- struct{}{} collector.Lock() - collector.count-- - collector.sinks = append(collector.sinks[0:s.id], collector.sinks[s.id+1:]...) + for i, v := range collector.sinks { + if s == v { + collector.sinks[i] = collector.sinks[len(collector.sinks)-1] + collector.sinks[len(collector.sinks)-1] = nil + collector.sinks = collector.sinks[:len(collector.sinks)-1] + break + } + } collector.Unlock() } }