Great writeup! Another, and maybe slightly simpler, way of implementing thread-safe queues in Go is to use Goroutines that are thread-safe by default:
typeQueueGoRoutinestruct{capacityintqchanint}func(q*QueueGoRoutine)Insert(itemint)error{iflen(q.q)<int(q.capacity){q.q<-itemreturnnil}returnerrors.New("Queue is full")}func(q*QueueGoRoutine)Remove()(int,error){iflen(q.q)>0{item:=<-q.qreturnitem,nil}return0,errors.New("Queue is empty")}funcCreateQueueGoRoutine(capacityint)FifoQueue{return&QueueGoRoutine{capacity:capacity,q:make(chanint,capacity),}}
In my simple benchmark on my device, this implementation has a slightly better performance too:
Great writeup! Another, and maybe slightly simpler, way of implementing thread-safe queues in Go is to use Goroutines that are thread-safe by default:
In my simple benchmark on my device, this implementation has a slightly better performance too:
This is cool. I come from a Java background so channels weren't that intuitive for me. Thank you for taking the time to put the code. Super helpful.
Glad to help.