...

Source file src/github.com/docker/go-events/channel.go

Documentation: github.com/docker/go-events

     1  package events
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  )
     7  
     8  // Channel provides a sink that can be listened on. The writer and channel
     9  // listener must operate in separate goroutines.
    10  //
    11  // Consumers should listen on Channel.C until Closed is closed.
    12  type Channel struct {
    13  	C chan Event
    14  
    15  	closed chan struct{}
    16  	once   sync.Once
    17  }
    18  
    19  // NewChannel returns a channel. If buffer is zero, the channel is
    20  // unbuffered.
    21  func NewChannel(buffer int) *Channel {
    22  	return &Channel{
    23  		C:      make(chan Event, buffer),
    24  		closed: make(chan struct{}),
    25  	}
    26  }
    27  
    28  // Done returns a channel that will always proceed once the sink is closed.
    29  func (ch *Channel) Done() chan struct{} {
    30  	return ch.closed
    31  }
    32  
    33  // Write the event to the channel. Must be called in a separate goroutine from
    34  // the listener.
    35  func (ch *Channel) Write(event Event) error {
    36  	select {
    37  	case ch.C <- event:
    38  		return nil
    39  	case <-ch.closed:
    40  		return ErrSinkClosed
    41  	}
    42  }
    43  
    44  // Close the channel sink.
    45  func (ch *Channel) Close() error {
    46  	ch.once.Do(func() {
    47  		close(ch.closed)
    48  	})
    49  
    50  	return nil
    51  }
    52  
    53  func (ch *Channel) String() string {
    54  	// Serialize a copy of the Channel that doesn't contain the sync.Once,
    55  	// to avoid a data race.
    56  	ch2 := map[string]interface{}{
    57  		"C":      ch.C,
    58  		"closed": ch.closed,
    59  	}
    60  	return fmt.Sprint(ch2)
    61  }
    62  

View as plain text