Memory Management: The unused memory locations in the case of ordinary queues can be utilized in circular queues.
Traffic system: In computer controlled traffic system, circular queues are used to switch on the traffic lights one by one repeatedly as per the time set.
CPU Scheduling: Operating systems often maintain a queue of processes that are ready to execute or that are waiting for a particular event to occur.
Lock Free Queue: When high performance is required, we don’t want to use lock. Circular Queue can is the top 1 data structure for lock free queue.
packagecircular_queueimport("errors")typeCircularQueuestruct{nint64headint64tailint64data[]int}func(this*CircularQueue)IsEmpty()bool{returnthis.head==this.tail}func(this*CircularQueue)IsFull()bool{returnthis.tail-this.head==this.n-1}func(this*CircularQueue)Push(valueint)error{ifthis.IsFull(){returnerrors.New("The queue is full")}this.data[this.tail&(this.n-1)]=valuethis.tail+=1returnnil}func(this*CircularQueue)Pop()(valueint,errerror){ifthis.IsEmpty(){err=errors.New("The queue is empty")return}value=this.data[this.head&(this.n-1)]this.head+=1return}funcNew(nint64)(*CircularQueue,error){ifn&(n-1)!=0{returnnil,errors.New("n must be the power of 2")}return&CircularQueue{n:n,head:0,tail:0,data:make([]int,n,n),},nil}
packagecircular_queueimport("testing")funcTestQueue(t*testing.T){varnint64=7queue,err:=New(n)iferr==nil{t.Error("There should be an error")}n=8queue,err=New(n)iferr!=nil{t.Error("There should be no error")}ifqueue.IsEmpty()==false{t.Error("The queue should be empty now")}ifqueue.IsFull(){t.Error("The queue should not be full now")}fori:=1;i<8;i++{queue.Push(i)}ifqueue.IsEmpty(){t.Error("The queue should not be empty now")}ifqueue.IsFull()==false{t.Error("The queue shoule be full now")}fori:=1;i<8;i++{value,err:=queue.Pop()iferr!=nil{t.Error("There should be no error")}ifvalue!=i{t.Errorf("The value poped should be %d, but now is %d",i,value)}}ifqueue.IsEmpty()==false{t.Error("The queue should be empty now")}_,err=queue.Pop()iferr==nil{t.Error("There should be an error")}}