github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/queues/list_chan.go (about)

     1  // implements locking queues, using list and channel
     2  package goqueuestest
     3  
     4  import (
     5  	"container/list"
     6  )
     7  
     8  type LCFifo struct {
     9  	l    *list.List
    10  	lock chan int
    11  }
    12  
    13  func NewListCFifo() *LCFifo {
    14  	ch := make(chan int, 1)
    15  	ch <- 1
    16  	return &LCFifo{list.New(), ch}
    17  }
    18  
    19  func (q *LCFifo) Enqueue(value interface{}) {
    20  	<-q.lock
    21  	q.l.PushBack(value)
    22  	q.lock <- 1
    23  }
    24  
    25  func (q *LCFifo) Dequeue() (interface{}, bool) {
    26  	<-q.lock
    27  	if q.l.Len() == 0 {
    28  		q.lock <- 1
    29  		return nil, false
    30  	}
    31  	value := q.l.Remove(q.l.Front())
    32  	q.lock <- 1
    33  	return value, true
    34  }
    35  
    36  type LCLifo struct {
    37  	l    *list.List
    38  	lock chan int
    39  }
    40  
    41  func NewListCLifo() *LCLifo {
    42  	ch := make(chan int, 1)
    43  	ch <- 1
    44  	return &LCLifo{list.New(), ch}
    45  }
    46  
    47  func (q *LCLifo) Enqueue(value interface{}) {
    48  	<-q.lock
    49  	q.l.PushBack(value)
    50  	q.lock <- 1
    51  }
    52  
    53  func (q *LCLifo) Dequeue() (interface{}, bool) {
    54  	<-q.lock
    55  	if q.l.Len() == 0 {
    56  		q.lock <- 1
    57  		return nil, false
    58  	}
    59  	value := q.l.Remove(q.l.Back())
    60  	q.lock <- 1
    61  	return value, true
    62  }