How to implement a concurrent queue using channels and sync in Golang?

To implement a concurrent queue using channels and sync in Golang, you can follow these steps:

  1. Start by creating a structure to represent the concurrent queue. It will contain a channel for sending and receiving elements, as well as a mutex for synchronizing access to the queue.
type ConcurrentQueue struct { queue []interface{} enqueue chan interface{} dequeue chan struct{} mutex sync.Mutex }
  1. Create a function to initialize the concurrent queue. It should set up the channels and start a goroutine to handle enqueue and dequeue requests.
func NewConcurrentQueue() *ConcurrentQueue { q := &ConcurrentQueue{ queue: make([]interface{}, 0), enqueue: make(chan interface{}), dequeue: make(chan struct{}), } go func() { for { select { case <-q.dequeue: q.mutex.Lock() if len(q.queue) > 0 { q.queue = q.queue[1:] } q.mutex.Unlock() case elem := <-q.enqueue: q.mutex.Lock() q.queue = append(q.queue, elem) q.mutex.Unlock() } } }() return q }
  1. Define methods to enqueue and dequeue elements from the concurrent queue. These methods will send the enqueue or dequeue requests to the corresponding channels.
func (q *ConcurrentQueue) Enqueue(elem interface{}) { q.enqueue <- elem } func (q *ConcurrentQueue) Dequeue() interface{} { q.dequeue <- struct{}{} return <-q.enqueue }
  1. You can now use the concurrent queue by creating an instance and calling the enqueue and dequeue methods from multiple goroutines.
func main() { q := NewConcurrentQueue() go func() { for i := 0; i < 10; i++ { q.Enqueue(i) } }() go func() { for i := 0; i < 10; i++ { fmt.Println("Dequeued:", q.Dequeue()) } }() time.Sleep(time.Second) // Wait for goroutines to complete }

By using channels and sync.Mutex for synchronization, this implementation provides a concurrent queue that can be accessed safely and efficiently from multiple goroutines.