Wait with timeout

This commit is contained in:
2024-06-16 15:27:46 +02:00
parent ff0bff0eb1
commit d7dab5e41d
2 changed files with 53 additions and 29 deletions

View File

@@ -4,7 +4,6 @@ import (
"sync"
)
type RingBuffer struct {
buffer []string
size int
@@ -13,7 +12,6 @@ type RingBuffer struct {
mu sync.Mutex
}
func NewRingBuffer(size int) *RingBuffer {
return &RingBuffer{
buffer: make([]string, size),
@@ -23,7 +21,6 @@ func NewRingBuffer(size int) *RingBuffer {
}
}
func (rb *RingBuffer) Add(item string) {
rb.mu.Lock()
defer rb.mu.Unlock()
@@ -40,7 +37,6 @@ func (rb *RingBuffer) Add(item string) {
}
}
func (rb *RingBuffer) GetLast() (string, int) {
rb.mu.Lock()
defer rb.mu.Unlock()
@@ -52,19 +48,28 @@ func (rb *RingBuffer) GetLast() (string, int) {
return rb.buffer[rb.tail], rb.tail
}
func (rb *RingBuffer) WaitForNewItem() string {
var newItem string
rb.mu.Lock()
defer rb.mu.Unlock()
for {
rb.mu.Lock()
if rb.head != -1 && rb.tail != -1 && rb.buffer[rb.tail] != newItem {
newItem = rb.buffer[rb.tail]
rb.mu.Unlock()
break
}
rb.mu.Unlock()
if rb.tail == -1 {
return ""
}
return newItem
return rb.buffer[rb.tail]
}
func (rb *RingBuffer) IsEmpty() bool {
rb.mu.Lock()
defer rb.mu.Unlock()
return rb.head == -1
}
func (rb *RingBuffer) GetLastPosition() int {
rb.mu.Lock()
defer rb.mu.Unlock()
return rb.tail
}