Is there a queue implementation?

后端 未结 14 1160
时光取名叫无心
时光取名叫无心 2020-12-23 02:14

Can anyone suggest Go container for simple and fast FIF/queue, Go has 3 different containers: heap, list and vector. Which one is more

14条回答
  •  再見小時候
    2020-12-23 02:42

    I also implement the queue from slice as above. However, It's not thread-safe. So I decided to add a lock (mutex lock) to guarantee thread-safe.

    package queue
    
    import (
      "sync"
    )
    
    type Queue struct {
      lock *sync.Mutex
      Values []int
    }
    
    func Init() Queue {
      return Queue{&sync.Mutex{}, make([]int, 0)}
    }
    
    func (q *Queue) Enqueue(x int) {
      for {
        q.lock.Lock()
        q.Values = append(q.Values, x)
        q.lock.Unlock()
        return
      }
    }
    
    func (q *Queue) Dequeue() *int {
      for {
        if (len(q.Values) > 0) {
          q.lock.Lock()
          x := q.Values[0]
          q.Values = q.Values[1:]
          q.lock.Unlock()
          return &x
        }
        return nil
      }
      return nil
    }
    

    You can check my solution on github here simple queue

提交回复
热议问题