Documentation ¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Buffer ¶
type Buffer[T any] struct { // contains filtered or unexported fields }
Buffer is a thread-safe, generic data structure that allows multiple goroutines to produce and consume elements in a synchronized manner. It is implemented as a queue and uses channels to synchronize the goroutines. The Buffer should be initialized with the Init method before use.
func (*Buffer[T]) CleanBuffer ¶
func (b *Buffer[T]) CleanBuffer()
CleanBuffer removes all elements from the Buffer, effectively resetting it to an empty state. Precalculated elements are kept as they are no longer in the buffer but in the channel. It locks the firstMutex to ensure thread-safety during the operation.
This method is safe for concurrent use by multiple goroutines.
Note: This method assumes that the trimFrom method of the safeElement type is thread-safe.
If the Buffer is already empty, this method does nothing.
func (*Buffer[T]) Init ¶
Init initializes a Buffer instance. It ensures the initialization is done only once, even if called multiple times. It creates two channels and a condition variable, and starts two goroutines: one that listens for incoming messages on the send channel and adds them to the Buffer, and another that sends messages from the Buffer to the receive channel. This method should be called before using the Buffer.
Parameters:
- bufferSize: The size of the buffer for the send and receive channels. Must be a non-negative integer. If a negative integer is provided, the method will panic.
Returns:
- A send-only channel of type T. Messages sent to this channel are added to the Buffer.
- A receive-only channel of type T. Messages from the Buffer are sent to this channel.
Information: To close the buffer, just close the send-only channel. Once that is done, a cascade of events will happen:
- The goroutine that listens for incoming messages will stop listening and exit.
- The goroutine that sends messages from the Buffer to the receive channel will stop sending messages once the Buffer is empty, and then exit.
- The Buffer will be cleaned up.
func (*Buffer[T]) Wait ¶
func (b *Buffer[T]) Wait()
Wait is a method of the Buffer type. It blocks the calling goroutine until all goroutines launched by the Buffer have finished executing. This is achieved by waiting for the internal WaitGroup to be done.
This method is thread-safe and can be called from multiple goroutines.