github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/queues/list_mutex.go (about) 1 // implements locking queues, using list and mutex 2 package goqueuestest 3 4 import ( 5 "container/list" 6 "sync" 7 ) 8 9 type LFifo struct { 10 l *list.List 11 m sync.Mutex 12 } 13 14 func NewListFifo() *LFifo { 15 return &LFifo{list.New(), sync.Mutex{}} 16 } 17 18 func (q *LFifo) Enqueue(value interface{}) { 19 q.m.Lock() 20 q.l.PushBack(value) 21 q.m.Unlock() 22 } 23 24 func (q *LFifo) Dequeue() (interface{}, bool) { 25 q.m.Lock() 26 if q.l.Len() == 0 { 27 q.m.Unlock() 28 return nil, false 29 } 30 value := q.l.Remove(q.l.Front()) 31 q.m.Unlock() 32 return value, true 33 } 34 35 type LLifo struct { 36 l *list.List 37 m sync.Mutex 38 } 39 40 func NewListLifo() *LLifo { 41 return &LLifo{list.New(), sync.Mutex{}} 42 } 43 44 func (q *LLifo) Enqueue(value interface{}) { 45 q.m.Lock() 46 q.l.PushBack(value) 47 q.m.Unlock() 48 } 49 50 func (q *LLifo) Dequeue() (interface{}, bool) { 51 q.m.Lock() 52 if q.l.Len() == 0 { 53 q.m.Unlock() 54 return nil, false 55 } 56 value := q.l.Remove(q.l.Back()) 57 q.m.Unlock() 58 return value, true 59 }