public
Last active

an absurd queue implementation with higher-order channels

  • Download Gist
queue.go
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
package main
 
import (
"fmt"
"math/rand"
"time"
)
 
type Queue struct {
data []interface{}
n int
cpop chan chan interface{}
cpush chan interface{}
}
 
func New(n int) *Queue {
q := &Queue{
data: make([]interface{}, 0, n),
cpop: make(chan chan interface{}),
cpush: make(chan interface{}),
}
go q.run()
return q
}
 
func (q *Queue) run() {
for {
select {
case c := <-q.cpop:
c <- q.pop()
case v := <-q.cpush:
q.push(v)
}
}
}
 
func (q *Queue) Push(v interface{}) {
q.cpush <- v
}
 
func (q *Queue) push(v interface{}) {
q.data = append(q.data, v)
}
 
func (q *Queue) Pop() (interface{}, bool) {
if len(q.data) == 0 {
return nil, false
}
c := make(chan interface{})
q.cpop <- c
return <-c, true
}
 
func (q *Queue) pop() interface{} {
if len(q.data) == 0 {
return nil
}
defer func() { q.data = q.data[1:] }()
return q.data[0]
}
 
func (q *Queue) Empty() bool {
return len(q.data) == 0
}
 
func main() {
q := New(100)
rand.Seed(time.Now().Unix())
 
// producer
go func() {
for {
switch rand.Intn(3) {
case 0:
q.Push(1)
case 1:
q.Push("stanley")
case 2:
q.Push(struct {
X int
Y int
}{
X: 5,
Y: 10,
})
}
time.Sleep(time.Millisecond * time.Duration(rand.Intn(10)))
}
}()
 
// consumer
for {
v, ok := q.Pop()
if ok {
fmt.Println(v)
}
time.Sleep(time.Millisecond * time.Duration(rand.Intn(10)))
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.