github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/internal/benchmark/linkedq/linkedq.go (about)

     1  package linkedq
     2  
     3  import "sync"
     4  
     5  type LinkedQueue struct {
     6  	head *linkedqueueNode
     7  	tail *linkedqueueNode
     8  	mu   sync.Mutex
     9  }
    10  
    11  type linkedqueueNode struct {
    12  	value uint64
    13  	next  *linkedqueueNode
    14  }
    15  
    16  func New() *LinkedQueue {
    17  	node := new(linkedqueueNode)
    18  	return &LinkedQueue{head: node, tail: node}
    19  }
    20  
    21  func (q *LinkedQueue) Enqueue(value uint64) bool {
    22  	q.mu.Lock()
    23  	q.tail.next = &linkedqueueNode{value: value}
    24  	q.tail = q.tail.next
    25  	q.mu.Unlock()
    26  	return true
    27  }
    28  
    29  func (q *LinkedQueue) Dequeue() (uint64, bool) {
    30  	q.mu.Lock()
    31  	if q.head.next == nil {
    32  		q.mu.Unlock()
    33  		return 0, false
    34  	} else {
    35  		value := q.head.next.value
    36  		q.head = q.head.next
    37  		q.mu.Unlock()
    38  		return value, true
    39  	}
    40  }