Fun thought exercise -- here's another approach.

https://play.golang.org/p/Xu7iWhY4PUQ
package main

import (
"fmt"
"math/rand"
"sort"
"time"
"strconv"
)

type PriorityStruct struct {
P    int
name string
}

const BUFSIZE = 10

type PriorityChan chan PriorityStruct
type PriorityBuf []PriorityStruct

func (s PriorityBuf) Len() int {
return len(s)
}
func (s PriorityBuf) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s PriorityBuf) Less(i, j int) bool {
return s[i].P < s[j].P
}

func Sender(pchan PriorityChan) {
for {
randNum := rand.Intn(3)
pchan <- PriorityStruct{
P:    randNum,
name: "Bob-" + strconv.Itoa(randNum),
}
time.Sleep(10 * time.Millisecond)
}
}

func Prioritize(inChan PriorityChan, outChan PriorityChan) {
for {
buf := make(PriorityBuf, BUFSIZE)
for i, _ := range buf {
buf[i] = <-inChan
}
sort.Sort(buf)
for i, _ := range buf {
outChan <- buf[i]
}
}
}

func Receiver(rchan PriorityChan) {
for {
fmt.Printf("%v\n", <-rchan)
}
}

func main() {
inChan := make(PriorityChan)
outChan := make(PriorityChan)
go Sender(inChan)
go Receiver(outChan)
go Prioritize(inChan, outChan)
<- time.After(5 * time.Second)
}

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CADgM4WLa32XWs7-jSM6J3p_QMMN9tnk%3DSjNxOSg34XZ7PHJDgw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to