Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(342)

Unified Diff: worker/simpleworker.go

Issue 67080043: Simpleworker implemention
Patch Set: Created 11 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: worker/simpleworker.go
=== added file 'worker/simpleworker.go'
--- worker/simpleworker.go 1970-01-01 00:00:00 +0000
+++ worker/simpleworker.go 2014-02-21 19:09:03 +0000
@@ -0,0 +1,46 @@
+// Copyright 2014 Canonical Ltd.
+// Licensed under the AGPLv3, see LICENCE file for details.
+
+package worker
+
+// simpleWorker is a type that just provides very simple Kill and Wait
+// mechanisms through the use of a couple channels. The channels are only used
rog 2014/02/24 17:57:36 A slightly different suggestion: // simpleWorker
natefinch 2014/02/24 19:26:43 Sounds good. Done.
+// for their "block until closed" feature. Nothing is ever sent over them.
+type simpleWorker struct {
+ stopc chan struct{}
+ done chan struct{}
+ err error
+}
+
+// NewSimpleWorker returns a worker that runs the given function. The
+// stopCh argument will be closed when the worker is killed. The error returned
+// by the doWork function will be returned by the worker's Wait function.
+func NewSimpleWorker(doWork func(stopCh <-chan struct{}) error) Worker {
+ w := &simpleWorker{
+ stopc: make(chan struct{}),
+ done: make(chan struct{}),
+ }
+ go func() {
+ w.err = doWork(w.stopc)
+ close(w.done)
+ }()
+ return w
+}
+
+// Kill implements Worker.Kill() and will close the channel given to the doWork
+// function.
+func (w *simpleWorker) Kill() {
+ defer func() {
+ // Allow any number of calls to Kill - the second and subsequent calls
+ // will panic, but we don't care.
+ recover()
+ }()
+ close(w.stopc)
+}
+
+// Wait implements Worker.Wait(), and will return the error returned by
+// the doWork function.
+func (w *simpleWorker) Wait() error {
+ <-w.done
+ return w.err
+}
« no previous file with comments | « [revision details] ('k') | worker/simpleworker_test.go » ('j') | worker/simpleworker_test.go » ('J')

Powered by Google App Engine
RSS Feeds Recent Issues | This issue
This is Rietveld f62528b