Ubuntu Pastebin

Paste from william at Sun, 21 Jun 2015 09:37:35 +0000

Download as text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
type ContextFunc func(interface{}) error

type Operation interface {
	Run(stop <-chan struct{}, getContext ContextFunc) error
}

type Serializer interface {
	worker.Worker
	Send(op Operation) error
}

func NewSerializer(getContext ContextFunc) Serializer {
	s := &serializer{
		ops: make(chan Operation),
	}
	go func() {
		defer s.tomb.Done()
		s.tomb.Kill(s.loop(getContext))
	}()
	return s
}

type serializer struct {
	tomb tomb.Tomb
	ops  chan Operation
}

func (s *serializer) Send(op Operation) error {
	select {
	case <-s.tomb.Dying():
		return errStopped
	case s.ops <- op:
		return nil
	}
}

func (s *serializer) loop(getContext ContextFunc) error {
	for {
		select {
		case <-s.tomb.Dying():
			return tomb.ErrDying
		case op := <-s.ops:
			if err := op.Run(getContext, s.tomb.Dying()); err != nil {
				return errors.Trace(err)
			}
		}
	}
}
Download as text