一、是什么
一種先進(jìn)先出的線性表數(shù)據(jù)結(jié)構(gòu),只支持入隊(duì)和出隊(duì)操作
二、使用場(chǎng)景
-
MySQL連接池 -
Redis單線程特性 - 分布式消息隊(duì)列
三、工作原理
隊(duì)尾插入元素,隊(duì)頭刪除元素
四、隊(duì)列類型
-
順序隊(duì)列:
數(shù)組實(shí)現(xiàn)的就是順序隊(duì)列(有數(shù)據(jù)搬移操作) -
循環(huán)隊(duì)列:
將數(shù)組的首尾相連,形成一個(gè)環(huán)(沒(méi)有數(shù)據(jù)搬移操作) -
阻塞隊(duì)列:
當(dāng)隊(duì)列為空時(shí),從隊(duì)頭取數(shù)據(jù)會(huì)被阻塞;當(dāng)隊(duì)列已滿時(shí),插入數(shù)據(jù)的操作將被阻塞,形成一個(gè)生產(chǎn)者-消費(fèi)者模型。 -
并發(fā)隊(duì)列:
在多線程情況下, 會(huì)有多個(gè)線程同時(shí)操作隊(duì)列,此時(shí)如果是線程安全的隊(duì)列我們就叫作并發(fā)隊(duì)列。一般使用CAS(類似樂(lè)觀鎖)和鎖來(lái)實(shí)現(xiàn)并發(fā)隊(duì)列。
四、實(shí)現(xiàn)
-
代碼實(shí)現(xiàn)
type list []int
func NewList() *list {
newList := make(list, 0)
return &newList
}
func listPush(newList *list, a ...int) {
*newList = append(*newList, a...)
}
func listPop(newList *list) (listObj int) {
length := len(*newList)
if length <= 0 {
return
}
listObj = (*newList)[0]
*newList = (*newList)[1:length]
return
}
-
Redis實(shí)現(xiàn)
rpush + lpop = list(隊(duì)列)
五、優(yōu)劣
- 優(yōu)點(diǎn):
- 不涉及到數(shù)組搬移時(shí),出隊(duì)和入隊(duì)的時(shí)間復(fù)雜度都為
O(1) - 操作受限,使用比較可控,不容易出錯(cuò)(和數(shù)組、鏈表相比較)
- 缺點(diǎn):
- 在內(nèi)存中,隊(duì)列結(jié)構(gòu)里的數(shù)據(jù)大小和生命周期是固定的,缺乏靈活性
六、替代性技術(shù)
- 數(shù)組
- 鏈表
- 棧