Last active
March 28, 2016 03:51
-
-
Save mDibyo/722cada08f42427fc938 to your computer and use it in GitHub Desktop.
A simple thread-safe implementation of a FIFO queue backed by a linked-list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package queue | |
| import ( | |
| "container/list" | |
| "sync" | |
| ) | |
| // Queue is a thread-safe FIFO queue implemented on top of a linked list. | |
| type Queue struct { | |
| list list.List | |
| mutex sync.Mutex | |
| } | |
| // Len returns the number of values in the queue. | |
| func (q *Queue) Len() int { | |
| return q.list.Len() | |
| } | |
| // Push inserts a value at the back of the queue. | |
| func (q *Queue) Push(value interface{}) { | |
| q.mutex.Lock() | |
| defer q.mutex.Unlock() | |
| q.list.PushBack(value) | |
| } | |
| // Pop removes the value at the front of the queue and returns it. | |
| func (q *Queue) Pop() interface{} { | |
| q.mutex.Lock() | |
| defer q.mutex.Unlock() | |
| if q.list.Len() == 0 { | |
| return nil | |
| } | |
| return q.list.Remove(q.list.Front()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment