wq

package module
v0.0.0-...-e415d6e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 18, 2022 License: MIT Imports: 2 Imported by: 0

README

wq

Stupid lock-free work queue.

This was mostly an experiment, and hasn't been throughly tested, but should be equivalent or faster than a channel based one.

>> go test -benchmem -run=^$ -bench=. -benchtime=5s .
goos: linux
goarch: amd64
pkg: github.com/Karitham/wq
cpu: 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
BenchmarkQueue-8        52272778               120.6 ns/op             0 B/op          0 allocs/op
BenchmarkChans-8        18827577               322.6 ns/op             0 B/op          0 allocs/op
PASS
ok      github.com/Karitham/wq  13.076s

It has the downside of requiring you to know your queue size ahead of time, which dictates the worker count.

It is also a busy queue, which works best if your producer are faster than your consumers.

Usage

q := wq.New(func(v *int) { fmt.Println(*v) })

for i := 0; i < 1000; i++ {
    i := i // copy (else it would be a pointer to the same value)
    q.EnQ(&i) // enqueue i
}

q.Wait() // wait for all workers to be done

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithNoStart

func WithNoStart() func(*Option)

WithNoStart disables starting any workers.

func WithWorkerCount

func WithWorkerCount(wCount int) func(*Option)

WithWorkerCount sets the number of workers to start.

Types

type Option

type Option struct {
	// contains filtered or unexported fields
}

type WQueue

type WQueue[T any] struct {
	// contains filtered or unexported fields
}

WQueue is a queue of work to be done (with associated workers).

func New

func New[T any](w func(*T), opts ...func(*Option)) *WQueue[T]

New returns a new WorkQueue of the given worker count.

func (*WQueue[T]) Close

func (wq *WQueue[T]) Close()

Close closes the queue.

func (*WQueue[T]) Closed

func (wq *WQueue[T]) Closed() bool

Closed returns true if the queue is closed.

func (*WQueue[T]) Drain

func (wq *WQueue[T]) Drain() []T

Drain removes all items from the queue and returns them.

func (*WQueue[T]) EnQ

func (wq *WQueue[T]) EnQ(item *T)

EnQ adds a work item to the queue.

func (*WQueue[T]) Run

func (wq *WQueue[T]) Run(fn func(*T))

Run starts workers and executes the given work function for each item in the queue.

func (*WQueue[T]) Wait

func (wq *WQueue[T]) Wait()

Wait waits for all workers to finish.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL