This is a creation in Article, where the information may have evolved or changed.
Lock-free queue for scenarios:
Two threads of interaction data, one thread production data, another thread consuming data, high efficiency
Cons: Need to use fixed allocated space, can not dynamically increase/decrease length, there is space waste and can not expand the space problem
Package Mainimport ( "FMT" "Reflect" "strings" "Time ")
Type loopqueue struct{start int end int length int name string data []interface{}}f UNC (this* loopqueue) initqueue (length int, name string) bool{if nil = = This | | length <= 0{return F Alse} this.data = make ([]interface{}, Length) this.length = length THIS.name = name This.st Art = 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 = th Is.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 = (st Art+1)% this.length return True, Startvalue}func (this* loopqueue) isEmpty () bool{If nil = this{PA Nic ("Loopqueue is nil")} if This.getstart () = = This.getend () {return true} return F Alse}func (this* loopqueue) isfull () bool{If nil = this{Panic ("Loopqueue is nil")} if thi S.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 loopqu Euefunc 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)}}//implementation Ring queue Func main () {Q.initqueue (Ten, "test") go Create () go Consum () for{ Time. Sleep (1E9)}}
569 reads