Last active
March 15, 2018 15:31
-
-
Save frankbryce/151f172270d600958740312f1cd31705 to your computer and use it in GitHub Desktop.
An simple interface and implementation for concurrent queue in go
This file contains 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
// Can be any backing type, even 'interface{}' if desired. | |
// See stackoverflow.com/q/11403050/3960399 for type conversion instructions. | |
type IntConcurrentQueue interface { | |
// Inserts the int into the queue | |
Enqueue(int) | |
// Will return error if there is nothing in the queue or if Close() was already called | |
DequeueNonBlocking() (int, error) | |
// Will block until there is a value in the queue to return. | |
// Will error if Close() was already called. | |
DequeueBlocking() (int, error) | |
// Close should be called with defer after initializing | |
Close() | |
} | |
func GetIntConcurrentQueue() IntConcurrentQueue { | |
return &intChannelQueue{c: make(chan int)} | |
} | |
type intChannelQueue struct { | |
c chan int | |
} | |
func (q *intChannelQueue) Enqueue(i int) { | |
q.c <- i | |
} | |
func (q *intChannelQueue) DequeueNonBlocking() (int, error) { | |
select { | |
case i, ok := <-q.c: | |
if ok { | |
return i, nil | |
} else { | |
return 0, fmt.Errorf("queue was closed") | |
} | |
default: | |
return 0, fmt.Errorf("queue has no value") | |
} | |
} | |
func (q *intChannelQueue) DequeueBlocking() (int, error) { | |
i, ok := <-q.c | |
if ok { | |
return i, nil | |
} | |
return 0, fmt.Errorf("queue was closed") | |
} | |
func (q *intChannelQueue) Close() { | |
close(q.c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment