仅供参考,如下:
package messageQueue
import (
"fmt"
"sync"
"time"
)
type Message interface {
}
type MessageQueue struct {
messages []Message
mutex *sync.Mutex
ch chan int
}
func (queue *MessageQueue) Create() *MessageQueue {
queue.messages = []Message{}
queue.mutex = &sync.Mutex{}
queue.ch = make(chan int, 100000)
return queue
}
func (queue *MessageQueue) Pop(waitMilliSeconds int) *Message {
if waitMilliSeconds > 0 {
timeout := time.After(time.Duration(waitMilliSeconds) * time.Millisecond)
for {
select {
case <-queue.ch:
fmt.Println("channel timeout")
goto _Out
case <-timeout:
fmt.Println("wait timeout")
goto _Out
}
}
} else {
<-queue.ch
}
_Out:
queue.mutex.Lock()
if len(queue.messages) == 0 {
queue.mutex.Unlock()
return nil
}
message := queue.messages[0]
queue.messages = queue.messages[1:]
queue.mutex.Unlock()
return &message
}
func (queue *MessageQueue) Push(message Message) {
queue.mutex.Lock()
queue.messages = append(queue.messages, message)
queue.mutex.Unlock()
queue.ch <- 1
}
func (queue *MessageQueue) IsEmpty() bool {
queue.mutex.Lock()
l := len(queue.messages)
queue.mutex.Unlock()
return l == 0
}
func (queue *MessageQueue) Size() int {
queue.mutex.Lock()
l := len(queue.messages)
queue.mutex.Unlock()
return l
}
使用参考另一篇博客。