Browse Source

Optimization

Vova Tkach 5 years ago
parent
commit
253b45de0a
2 changed files with 9 additions and 6 deletions
  1. 2 2
      main.go
  2. 7 4
      worker/worker.go

+ 2 - 2
main.go

@@ -41,12 +41,12 @@ func main() {
 		fmt.Printf("Worker #3 one tick\n")
 		time.Sleep(2 * time.Second)
 		fmt.Printf("Worker #3 Exit\n")
-		w.Finish()
+		w.Shutdown(nil)
 	})
 
 	time.Sleep(3 * time.Second)
 
-	w1.Finish()
+	w1.Shutdown(nil)
 
 	if err := w2.Shutdown(nil); err != nil {
 		fmt.Printf("Worker #2 shutdown error: %s\n", err.Error())

+ 7 - 4
worker/worker.go

@@ -8,6 +8,7 @@ type Worker struct {
 	ctx    context.Context
 	cancel context.CancelFunc
 	chDone chan bool
+	stop   bool
 }
 
 type Callback func(ctx context.Context, w *Worker)
@@ -35,6 +36,12 @@ func (this *Worker) doit(f func(ctx context.Context, w *Worker)) *Worker {
 }
 
 func (this *Worker) Shutdown(ctx context.Context) error {
+	if this.stop {
+		return nil
+	}
+
+	this.stop = true
+
 	ctxb := ctx
 	if ctxb == nil {
 		ctxb = context.Background()
@@ -49,7 +56,3 @@ func (this *Worker) Shutdown(ctx context.Context) error {
 		return ctxb.Err()
 	}
 }
-
-func (this *Worker) Finish() {
-	this.cancel()
-}