這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
無鎖隊列適用情境:
兩個線程之間的互動資料, 一個線程生產資料, 另外一個線程消費資料,效率高
缺點:需要使用固定分配的空間,不能動態增加/減少長度,存在空間浪費和無法擴充空間問題
package mainimport ( "fmt" "reflect" "strings" "time")
type LoopQueue struct{ start int end int length int name string data []interface{}}func (this* LoopQueue)InitQueue(length int, name string)bool{ if nil == this || length <= 0{ return false } this.data = make([]interface{}, length) this.length = length this.name = name this.start = 0 this.end = 0 return true}func (this* LoopQueue)Push(data interface{})bool{ if nil == this{ panic("LoopQueue is nil") } if this.isFull(){ return false } var end int = this.getEnd() this.data[end] = data this.end = (end+1)%this.length return true}func (this* LoopQueue)Pop() (bool, interface{}) { if nil == this{ panic("LoopQueue is nil") } if this.isEmpty(){ return false, nil } var start = this.getStart() var startValue interface{} = this.data[start] this.start = (start+1) % this.length return true, startValue}func (this* LoopQueue)isEmpty()bool{ if nil == this{ panic("LoopQueue is nil") } if this.getStart() == this.getEnd(){ return true } return false}func (this* LoopQueue)isFull()bool{ if nil == this{ panic("LoopQueue is nil") } if this.getEnd() +1 == this.getStart(){ return true } return false}func (this* LoopQueue)getStart()int{ return this.start % this.length}func (this* LoopQueue)getEnd()int{ return this.end % this.length}var Q LoopQueuefunc Create(){ var index int = 0 for{ ret := Q.Push(index) if ret{ fmt.Println("PushOk", "index=", index) index++ }else{ fmt.Println("PushError", "index=", index) } time.Sleep(1e9) }}func Consum(){ for{ ret, data := Q.Pop() if ret{ fmt.Println("PopSucc", "data=",data) }else{ fmt.Println("PopError") } time.Sleep(1e9) }}//實現環形隊列func main(){ Q.InitQueue(10, "test") go Create() go Consum() for{ time.Sleep(1e9) }}
569 次點擊