我们知道类似优先级队列是使用heap堆栈来实现的。 优先级队列的用途我就不多说了,一般是用来做任务权重分配的。

    下面priority_queue优先级库是在github.com找到的。 看了下他的源代码实现,得知他不是线程安全的。   如果要实现数据的线程安全,需要用sync lock实现全局锁,保证数据的原子性。

 

#xiaorui.cc

package main

import (
	"fmt"
	"github.com/gansidui/priority_queue"
)

type Node struct {
	priority int
	value    string
}

func (this *Node) Less(other interface{}) bool {
	return this.priority < other.(*Node).priority
}

func main() {
	q := priority_queue.New()

	q.Push(&Node{priority: 8, value: "8"})
	q.Push(&Node{priority: 7, value: "7"})
	q.Push(&Node{priority: 9, value: "9"})
	q.Push(&Node{priority: 2, value: "2"})
	q.Push(&Node{priority: 4, value: "4"})
	q.Push(&Node{priority: 3, value: "3"})
	q.Push(&Node{priority: 5, value: "5"})

	x := q.Top().(*Node)
	fmt.Println(x.priority, x.value)

	for q.Len() > 0 {
		x = q.Pop().(*Node)
		fmt.Println(x.priority, x.value)
	}
}