synchronization - 如何将这段代码转换为非阻塞和无锁?

标签 synchronization go queue nonblocking

我有队列,女巫必须有不断增长的缓冲区,这不包括我在 go 中使用缓冲 channel 。

经过一番谷歌搜索后,我想出了这段代码:

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
}

有什么方法可以将其转换为非阻塞和无锁队列吗?

最佳答案

Evan Huus's channels package提供ResizableChannel类型似乎可以提供您想要的内容。

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().

关于synchronization - 如何将这段代码转换为非阻塞和无锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21931545/

相关文章:

mysql - 在不同服务器上同步 MySQL 库的最佳方法

go - 当处理程序达到最大客户端限制时返回错误

java - 基于双端队列数组

c++ - 为什么 'wait with predicate'解决了条件变量的 'lost wakeup'?

swift - 如何在 Swift 中将已删除的对象与 Ensembles Framework 同步(使用 Dropbox)

戈朗 : how to explain the type assertion efficiency?

c - 我在 queue.h 中的修改是否由 Berkeley 实现?

c++ - 删除列表中的旧值并添加新值

java - 使用 3 个 PetersonLock 的数组来同步 4 个进程

Golang XML 解析