sync

package
v0.0.0-...-2597ab7 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2023 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package sync provides synchronisation primitives not available in the standard sync package.

Index

Constants

This section is empty.

Variables

View Source
var ErrToggleClosed = errors.New("toggle closed")

ErrToggleClosed is returned by Toggle.Wait() if Toggle.Close() was called.

Functions

This section is empty.

Types

type Toggle

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

A Toggle allows for Wait()ing until a condition is true. Unlike a broadcast mechanism that may be missed if waiting begins after a signal, waiting on an already "on" Toggle returns immediately.

The zero value for a Toggle is equivalent to Set(false). A Toggle MUST NOT be copied as it contains a sync.Mutex.

Toggle.Set(true) is a replacement for sync.Cond.Broadcast().

The implementation uses a channel with a single-item buffer. When Set() to true, the Toggle adds an item to the buffer, and when Set() to false, it removes said item. All calls to Wait() receive on the channel to unblock, and then immediately return the item. This allows for Context cancellation to be honoured.

func (*Toggle) Close

func (t *Toggle) Close()

Close closes the Toggle. All Wait()ers, current and future, unblock and return ErrToggleClosed.

func (*Toggle) Set

func (t *Toggle) Set(state bool)

Set sets the state of the Toggle. If the state is true, all current and future calls to Wait() will unblock. Calls to Set are idempotent.

Behaviour of Set() is undefined on a Close()d Toggle.

func (*Toggle) State

func (t *Toggle) State() bool

State returns the last value sent to Set(), or false if Set() is yet to be called.

func (*Toggle) Wait

func (t *Toggle) Wait(ctx context.Context) error

Wait blocks until the Toggle is Set() to true. If the last call to Set() was Set(true) then Wait unblocks immediately.

Jump to

Keyboard shortcuts

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