package main
import (
"context"
"fmt"
"sync"
"time"
)
type BlockingQueue[T any] chan T
func NewBlockingQueue[T any](queueSize int) BlockingQueue[T] {
return make(chan T, queueSize)
}
func (q BlockingQueue[T]) Push(value T) {
q <- value
}
func (q BlockingQueue[T]) TryPush(value T, timeout time.Duration) bool {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
select {
case q <- value:
return true
case <-ctx.Done():
return false
}
}
func (q BlockingQueue[T]) Poll() T {
return <-q
}
func (q BlockingQueue[T]) TryPoll(timeout time.Duration) (result T, ok bool) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
select {
case result = <-q:
return result, true
case <-ctx.Done():
return result, false
}
}
func (q BlockingQueue[T]) Size() int {
return len(q)
}
func main() {
l := 100000
queue := NewBlockingQueue[int](5000)
go fmt.Println(queue.TryPush(10000000, time.Second*10))
go fmt.Println(queue.TryPoll(time.Second * 10))
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < l; i++ {
queue.Push(i)
}
}()
go func() {
defer wg.Done()
for i := 0; i < l; i++ {
fmt.Println(queue.Poll())
}
}()
wg.Wait()
}
BlockingQueue的简单实现
最新推荐文章于 2023-11-16 16:49:38 发布