Created
August 23, 2024 22:09
-
-
Save DeedleFake/8aab4afb67fae88224c4e594d51d0ce0 to your computer and use it in GitHub Desktop.
Channel server example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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