github.com/woremacx/kocha@v0.7.1-0.20150731103243-a5889322afc9/event/memory/queue.go (about) 1 package memory 2 3 import "github.com/woremacx/kocha/event" 4 5 // EventQueue implements the Queue interface. 6 // This doesn't require the external storages such as Redis. 7 // Note that EventQueue isn't persistent, this means that queued data may be 8 // lost by crash, shutdown or status of not running. 9 // If you want to do use a persistent queue, please use another Queue 10 // implementation that supports persistence. 11 // Also queue won't be shared between different servers but will be shared 12 // between other workers in same server. 13 type EventQueue struct { 14 c chan string 15 done chan struct{} 16 exit chan struct{} 17 } 18 19 // New returns a new EventQueue. 20 func (q *EventQueue) New(n int) event.Queue { 21 if q.c == nil { 22 q.c = make(chan string, n) 23 } 24 if q.done == nil { 25 q.done = make(chan struct{}) 26 } 27 if q.exit == nil { 28 q.exit = make(chan struct{}) 29 } 30 return &EventQueue{ 31 c: q.c, 32 done: q.done, 33 exit: q.exit, 34 } 35 } 36 37 // Enqueue adds data to queue. 38 func (q *EventQueue) Enqueue(data string) error { 39 q.c <- data 40 return nil 41 } 42 43 // Dequeue returns the data that fetch from queue. 44 func (q *EventQueue) Dequeue() (data string, err error) { 45 select { 46 case data = <-q.c: 47 return data, nil 48 case <-q.done: 49 defer func() { 50 q.exit <- struct{}{} 51 }() 52 return "", event.ErrDone 53 } 54 } 55 56 // Stop wait for Dequeue to complete then will stop a queue. 57 func (q *EventQueue) Stop() { 58 q.done <- struct{}{} 59 <-q.exit 60 }