-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplicator.go
60 lines (50 loc) · 912 Bytes
/
replicator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"context"
"fmt"
"sync"
"time"
)
type replicator[T any] struct {
sync.Mutex
consumers []chan T
c chan T
}
func newReplicator[T any](ctx context.Context) *replicator[T] {
r := &replicator[T]{
consumers: make([]chan T, 0),
c: make(chan T),
}
go func() {
for {
select {
case <-ctx.Done():
return
case item := <-r.c:
for _, consumer := range r.consumers {
fmt.Println("item", item)
select {
case consumer <- item:
case <-time.After(10 * time.Millisecond):
continue
}
}
}
}
}()
return r
}
func (r *replicator[T]) consume() chan T {
consumer := make(chan T)
defer lockUnlock(r)
r.consumers = append(r.consumers, consumer)
return consumer
}
func (r *replicator[T]) produce(item T) chan struct{} {
wait := make(chan struct{})
go func() {
defer close(wait)
r.c <- item
}()
return wait
}