سؤال

I have queue, witch has to have growing buffer, this excludes usage of buffered channels in go for me.

After some google searching I've come up with this code:

import (
    "sync"
)

type Queue struct {
    nodes []interface{}
    head, tail, count int
    lck sync.RWMutex
}

func (q *Queue) Enqueue(v interface{}) {
    q.lck.Lock()
    defer q.lck.Unlock()

    if q.nodes == nil {
        q.nodes = make([]interface{}, 2)
    }

    if q.head == q.tail && q.count > 0 {
        nodes := make([]interface{}, len(q.nodes) * 2)
        copy(nodes, q.nodes[q.head:])
        copy(nodes[len(q.nodes) - q.head:], q.nodes[:q.head])
        q.head = 0
        q.tail = len(q.nodes)
        q.nodes = nodes
    }

    q.nodes[q.tail] = v
    q.tail = (q.tail + 1) % len(q.nodes)
    q.count++
}

func (q *Queue) Dequeue() interface{} {
    q.lck.Lock()
    defer q.lck.Unlock()

    if len(q.nodes) == 0 {
        return nil
    }

    node := q.nodes[q.head]
    q.head = (q.head + 1) % len(q.nodes)
    q.count--

    return node
}

func (q *Queue) Len() int {
    q.lck.RLock()
    defer q.lck.RUnlock()

    return q.count
}

Is there any way I could convert this to be non-blocking & lock-free queue?

هل كانت مفيدة؟

المحلول

Evan Huus's channels package provides the ResizableChannel type which seems to provide what you're after.

ResizableChannel implements the Channel interface with a resizable buffer between the input and the output. The channel initially has a buffer size of 1, but can be resized by calling Resize().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top