Queues - craterdog/go-component-framework GitHub Wiki

Overview

A queue is a collection that provides first-in-first-out (FIFO) semantics. Queues are often used for communication between different processes and therefore enforce synchronized access.

UML Diagram

A Quick Example

To whet your appetite, here is some short example code that demonstrates the use of queues.

package main

import (
	fmt "fmt"
	syn "sync"
	fra "github.com/craterdog/go-component-framework/v7"
)

func main() {
	// Create a wait group for synchronization.
	var wg = new(syn.WaitGroup)
	defer wg.Wait()

	// Create a new queue with a specific capacity using the module constructor shortcut.
	var queue = fra.QueueWithCapacity[int](12)
	fmt.Println("The empty queue:", queue)
	fmt.Println()

	// Add some values to the queue.
	for i := 1; i < 10; i++ {
		queue.AddValue(i)
		fmt.Println("Added value:", i)
	}
	fmt.Println()
	fmt.Println("The partially filled queue:", queue)
	fmt.Println()

	// Remove values from the queue in the background.
	wg.Add(1)
	go func() {
		defer wg.Done()
		var value int
		var ok = true
		for i := 1; ok; i++ {
			value, ok = queue.RemoveFirst()
			if ok {
				fmt.Println("Removed value:", value)
			}
		}
		fmt.Println("The closed queue:", queue)
		fmt.Println()
	}()

	// Add some more values to the queue.
	for i := 10; i < 31; i++ {
		queue.AddValue(i)
		fmt.Println("Added value:", i)
	}
	queue.CloseChannel()
}

NOTE: Due to the multiple go routines running in the example, the output will differ each time the example code is run.

Try it out in the Go Playground...