-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproducers.go
More file actions
55 lines (45 loc) · 870 Bytes
/
producers.go
File metadata and controls
55 lines (45 loc) · 870 Bytes
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
package queue
import (
"fmt"
)
type Producer[T any] struct {
queue *Queue[T]
channel chan T
closeChannel chan struct{}
errChannel chan error
}
func NewProducer[T any](q *Queue[T]) *Producer[T] {
channel := make(chan T)
closeChannel := make(chan struct{})
errChannel := make(chan error)
go func() {
for {
select {
case value := <-channel:
err := q.enqueue(value)
if err != nil {
errChannel <- fmt.Errorf("queue error: %w", err)
}
case <-closeChannel:
return
}
}
}()
return &Producer[T]{
queue: q,
channel: channel,
closeChannel: closeChannel,
}
}
func (c *Producer[T]) Produce() chan<- T {
return c.channel
}
func (c *Producer[T]) Close() error {
<-c.closeChannel
close(c.channel)
close(c.closeChannel)
return nil
}
func (c *Producer[T]) Err() <-chan error {
return c.errChannel
}