Documentation
¶
Overview ¶
Package trigger implements a channel-based condition variable.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cond ¶
type Cond struct {
// contains filtered or unexported fields
}
A Cond is a condition shared by multiple goroutines. The Cond.Ready method returns a channel that is closed when the condition is activated.
When a condition is first created it is inactive. While inactive, reads on the ready channel will block. The condition remains inactive until Cond.Set or Cond.Signal is called, either of which causes the current ready channel to be closed (and thus deliver a zero value). Once a condition has been activated, it remains active until it is reset. Use Cond.Reset to make it inactive again.
The Cond.Signal method activates and then immediately resets the condition, acting as Set and Reset done in a single step.
A zero Cond is ready for use, and is inactive, but must not be copied after any of its methods have been called.
Example ¶
package main
import (
"fmt"
"sync"
"github.com/creachadair/msync/trigger"
)
func printReady(c *trigger.Cond) {
select {
case <-c.Ready():
fmt.Println("condition ready")
default:
fmt.Println("condition not ready")
}
}
func main() {
var wg sync.WaitGroup
defer wg.Wait()
var c trigger.Cond
// Various tasks can wait for a condition to be ready.
r1 := c.Ready()
wg.Go(func() { <-r1; fmt.Println("task 1: ready") })
// When the condition is set, any waiters are woken.
c.Set()
// Once set, the condition remains set until reset.
printReady(&c)
// Once reset, the task is no longer ready.
c.Reset()
printReady(&c)
// Signaling the condition wakes any goroutines that are already waiting,
// then immediately resets the condition so that later arrivals will wait
// for a subsequent signal.
r2 := c.Ready()
wg.Go(func() { <-r2; fmt.Println("task 2: ready") })
fmt.Println("signal 1")
c.Signal()
// This goroutine arrives late, and will not be woken by the prior signal.
r3 := c.Ready()
wg.Go(func() { <-r3; fmt.Println("task 3: ready") })
printReady(&c)
// This signal will now wake the later arrival (task 3).
fmt.Println("signal 2")
c.Signal()
}
Output: task 1: ready condition ready condition not ready signal 1 task 2: ready condition not ready signal 2 task 3: ready
func (*Cond) Ready ¶
func (c *Cond) Ready() <-chan struct{}
Ready returns a channel that is closed when c is activated. If c is active when Ready is called, the returned channel will already be closed.
func (*Cond) Reset ¶
func (c *Cond) Reset()
Reset resets the condition. If it was already inactive, Reset has no effect.
func (*Cond) Set ¶
func (c *Cond) Set()
Set activates the condition. If it was already active, Set has no effect.
func (*Cond) Signal ¶
func (c *Cond) Signal()
Signal activates and immediately resets the condition. If the condition was already active, this is equivalent to Cond.Reset.