Documentation
¶
Overview ¶
Package syncbus provides an event bus for testing.
SyncBus can be used to execute test instructions in a concurrent program in a predefined order. It is expected to be used as a test hook shared between the production and the test code, or left nil if not required.
It provides a wait function for processes in goroutines that should continue only when a predefined signal is set, or the timeout expires. If the predefined signals are already set at the time of calling wait, the calling goroutine continues immediately. Once a signal is set, it stays so until it's cleared (reset).
Wait can expect one or more signals represented by keys. The signals don't need to be set simultaneously in order to release a waiting goroutine. A wait continues once all the signals that it depends on were set.
Example ¶
package main import ( "fmt" "sync" "time" "code.squareroundforest.org/arpio/syncbus" ) type Server struct { resource int mx sync.Mutex testBus *syncbus.SyncBus } func (s *Server) AsyncInit() { go func() { s.mx.Lock() defer s.mx.Unlock() s.resource = 42 s.testBus.Signal("initialized") }() } func (s *Server) Resource() int { s.mx.Lock() defer s.mx.Unlock() return s.resource } func main() { bus := syncbus.New(120 * time.Millisecond) s := &Server{} s.testBus = bus s.AsyncInit() if err := bus.Wait("initialized"); err != nil { fmt.Println("failed:", err) } fmt.Println(s.Resource()) }
Output: 42
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrTimeout = errors.New("timeout")
ErrTimeout is returned by Wait() when failed to receive all the signals in time.
Functions ¶
This section is empty.
Types ¶
type SyncBus ¶
type SyncBus struct {
// contains filtered or unexported fields
}
SyncBus can be used to synchronize goroutines through signals.
func New ¶
New creates and initializes a new SyncBus. It uses a shared timeout for all the Wait calls.
func (*SyncBus) Close ¶
func (b *SyncBus) Close()
Close tears down the SyncBus. If the receiver is nil, it is a noop.
func (*SyncBus) Reset ¶
func (b *SyncBus) Reset()
Reset clears all the signals.
If the receiver *SyncBus is nil, it is a noop.
func (*SyncBus) ResetSignals ¶
ResetSignals clears the set signals defined by the provided keys.
If the receiver *SyncBus is nil, or no key argument is passed to it, it is a noop.
func (*SyncBus) Signal ¶
Signal sets one or more signals represented by the keys.
If the receiver *SyncBus is nil, or no key argument is passed to it, it is a noop.