On Mon, Feb 16, 2015 at 6:31 AM, <
karl.m...@gmail.com> wrote:
>
> I am writing a program where I have a long running process and the main data
> structures will be a FIFO queue. Whats a good way to implement a queue?
>
> Slice is a first class container in go. I have found multiple user groups
> suggesting ways to make slice to emulate a queue.
> Dequeue
> x, a = a[len(a)-1], a[:len(a)-1]
>
> Enqueue
> a = append(a, x)
>
> The dequeue implementation makes me very nervous. The program is long
> running and millions of push/pops are expected. Randomly, the queue may
> get very long or it may get dequeue to len 0, over and over. If a slice is
> backed by a classic contiguous array, wont the unused front of the array
> left by the dequeue memory leak? The memory management of the append does
> not to lend its self to a long running queue either. Wont it just get more
> and more costly each time the backing array needs a resize?
Not really. The append function will allocate a new backing array
based on the current size of the slice itself, not the size of the
backing array of the slice. If you do something like this:
a = make([]int, 5)
a = a[4:]
a = append(a, 1, 2)
the append function will have to allocate a new backing array, because
there is no more room in the original one, and it will allocate a new
array of size 3 (plus some room to grow after those 3 elements).
> Second choice is a channel. I could just use the channel as a queue and
> push and pop as needed using the channel operators. But a channel does a
> lot of extra behavior. Perhaps it is too heavy weight to be used as a mere
> FIFO queue?
Channels are fairly lightweight, and they work nicely for a fixed-size
FIFO queue, provided values are pushed and popped by different
goroutines. It doesn't work to have one goroutine push a value on and
then pop it off later, because if the queue gets full the goroutine
will deadlock. Also, of course, you must set the size of the channel
buffer when you create the channel; there is no easy way to
dynamically adjust the queue size as the program executes.
Ian