github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xcontainer/queue/block_queue.go (about)

     1  package queue
     2  
     3  import (
     4  	"time"
     5  )
     6  
     7  type BlockQueue struct {
     8  	capacity int
     9  	ch       chan interface{}
    10  }
    11  
    12  func (q *BlockQueue) Capacity() int {
    13  	return q.capacity
    14  }
    15  
    16  func (q *BlockQueue) Push(x interface{}, timeout time.Duration) bool {
    17  	t := time.NewTimer(timeout)
    18  	select {
    19  	case q.ch <- x:
    20  		return true
    21  	case <-t.C:
    22  		return false
    23  	}
    24  }
    25  
    26  func (q *BlockQueue) Pop(timeout time.Duration) (interface{}, bool) {
    27  	t := time.NewTimer(timeout)
    28  	select {
    29  	case <-t.C:
    30  		return nil, false
    31  	case x := <-q.ch:
    32  		return x, true
    33  	}
    34  }
    35  
    36  func (q *BlockQueue) BlockPop() (interface{}, bool) {
    37  	val, ok := <-q.ch
    38  	return val, ok
    39  }
    40  
    41  func NewBlockingQueue(n int) *BlockQueue {
    42  	return &BlockQueue{
    43  		capacity: n,
    44  		ch:       make(chan interface{}, n),
    45  	}
    46  }