Skip to content

Instantly share code, notes, and snippets.

@DeedleFake
Created August 23, 2024 22:09
Show Gist options
  • Select an option

  • Save DeedleFake/8aab4afb67fae88224c4e594d51d0ce0 to your computer and use it in GitHub Desktop.

Select an option

Save DeedleFake/8aab4afb67fae88224c4e594d51d0ce0 to your computer and use it in GitHub Desktop.
Channel server example.
package example
type Queue[T any] struct {
push chan T
pop chan T
}
func NewQueue[T any](ctx context.Context) {
q := Queue{
push: make(chan T),
pop: make(chan T),
}
go q.run(ctx)
return &q
}
func (q *Queue[T]) Push() chan<- T {
return q.push
}
func (q *Queue[T]) Pop() <-chan T {
return q.pop
}
func (q *Queue[T]) run(ctx context.Context) {
var data []T
var pop chan T
var next T
for {
select {
case <-ctx.Done():
return
case d := <-q.push:
data = append(data, d)
pop = q.pop
next = data[0]
case pop <- next:
data = slices.Delete(data, 0, 1)
if len(data) == 0 {
pop = nil
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment