broadcast

package
v1.25.5 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2024 License: MIT Imports: 3 Imported by: 8

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Broadcast

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

Broadcast implements notifying waiters via a channel.

The zero-value of this struct is valid.

Example
// b guards currValue
var b Broadcast
var currValue int

go func() {
	// 0 to 9 inclusive
	for i := range 10 {
		<-time.After(time.Millisecond * 20)
		b.HoldLock(func(broadcast func(), getWaitCh func() <-chan struct{}) {
			currValue = i
			broadcast()
		})
	}
}()

var waitCh <-chan struct{}
var gotValue int
for {
	b.HoldLock(func(broadcast func(), getWaitCh func() <-chan struct{}) {
		gotValue = currValue
		waitCh = getWaitCh()
	})

	// last value
	if gotValue == 9 {
		// success
		break
	}

	// otherwise keep waiting
	<-waitCh
}

fmt.Printf("waited for value to increment: %v\n", gotValue)
Output:

waited for value to increment: 9

func (*Broadcast) HoldLock added in v1.6.0

func (c *Broadcast) HoldLock(cb func(broadcast func(), getWaitCh func() <-chan struct{}))

HoldLock locks the mutex and calls the callback.

broadcast closes the wait channel, if any. getWaitCh returns a channel that will be closed when broadcast is called.

func (*Broadcast) HoldLockMaybeAsync added in v1.11.1

func (c *Broadcast) HoldLockMaybeAsync(cb func(broadcast func(), getWaitCh func() <-chan struct{}))

HoldLockMaybeAsync locks the mutex and calls the callback if possible. If the mutex cannot be locked right now, starts a new Goroutine to wait for it.

func (*Broadcast) Wait added in v1.25.5

func (c *Broadcast) Wait(ctx context.Context, cb func(broadcast func()) (bool, error)) error

Wait waits for the cb to return true or an error before returning. When the broadcast channel is broadcasted, re-calls cb again to re-check the value. cb is called while the mutex is locked. Returns false, context.Canceled if ctx is canceled. Return nil if and only if cb returned true, nil.

Example
// b guards currValue
var b Broadcast
var currValue int

go func() {
	// 0 to 9 inclusive
	for i := range 10 {
		<-time.After(time.Millisecond * 20)
		b.HoldLock(func(broadcast func(), getWaitCh func() <-chan struct{}) {
			currValue = i
			broadcast()
		})
	}
}()

ctx := context.Background()
var gotValue int
b.Wait(ctx, func(broadcast func()) (bool, error) {
	gotValue = currValue
	return gotValue == 9, nil
})

fmt.Printf("waited for value to increment: %v\n", gotValue)
Output:

waited for value to increment: 9

Jump to

Keyboard shortcuts

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