To implement a concurrent queue using channels and sync in Golang, you can follow these steps:
type ConcurrentQueue struct {
queue []interface{}
enqueue chan interface{}
dequeue chan struct{}
mutex sync.Mutex
}
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
}
func (q *ConcurrentQueue) Enqueue(elem interface{}) {
q.enqueue <- elem
}
func (q *ConcurrentQueue) Dequeue() interface{} {
q.dequeue <- struct{}{}
return <-q.enqueue
}
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.