github.com/aaabigfish/gopkg@v1.1.0/internal/benchmark/linkedq/linkedq.go (about)

     1  // Copyright 2021 ByteDance Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package linkedq
    16  
    17  import "sync"
    18  
    19  type LinkedQueue struct {
    20  	head *linkedqueueNode
    21  	tail *linkedqueueNode
    22  	mu   sync.Mutex
    23  }
    24  
    25  type linkedqueueNode struct {
    26  	value uint64
    27  	next  *linkedqueueNode
    28  }
    29  
    30  func New() *LinkedQueue {
    31  	node := new(linkedqueueNode)
    32  	return &LinkedQueue{head: node, tail: node}
    33  }
    34  
    35  func (q *LinkedQueue) Enqueue(value uint64) bool {
    36  	q.mu.Lock()
    37  	q.tail.next = &linkedqueueNode{value: value}
    38  	q.tail = q.tail.next
    39  	q.mu.Unlock()
    40  	return true
    41  }
    42  
    43  func (q *LinkedQueue) Dequeue() (uint64, bool) {
    44  	q.mu.Lock()
    45  	if q.head.next == nil {
    46  		q.mu.Unlock()
    47  		return 0, false
    48  	} else {
    49  		value := q.head.next.value
    50  		q.head = q.head.next
    51  		q.mu.Unlock()
    52  		return value, true
    53  	}
    54  }