add day-10 + benchmarks

This commit is contained in:
2024-12-10 21:45:16 +00:00
parent 0236679639
commit 503082d822
22 changed files with 559 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
package queue
import "sync"
type ConcurrentQueue[T comparable] struct {
items []T
lock sync.Mutex
cond *sync.Cond
}
func New[T comparable]() *ConcurrentQueue[T] {
q := &ConcurrentQueue[T]{}
q.cond = sync.NewCond(&q.lock)
return q
}
func (q *ConcurrentQueue[T]) Enqueue(item T) {
q.lock.Lock()
defer q.lock.Unlock()
q.items = append(q.items, item)
q.cond.Signal()
}
func (q *ConcurrentQueue[T]) Dequeue() T {
q.lock.Lock()
defer q.lock.Unlock()
for len(q.items) == 0 {
q.cond.Wait()
}
item := q.items[0]
q.items = q.items[1:]
return item
}
func (q *ConcurrentQueue[T]) IsEmpty() bool {
return len(q.items) == 0
}