Browse Source

Allow additional vars

Vova Tkach 5 years ago
parent
commit
c4dabcf4be
2 changed files with 13 additions and 11 deletions
  1. 6 6
      main.go
  2. 7 5
      worker/worker.go

+ 6 - 6
main.go

@@ -11,7 +11,7 @@ import (
 func main() {
 	fmt.Printf("Start!\n")
 
-	w1 := worker.New(func(ctx context.Context, w *worker.Worker) {
+	w1 := worker.New(func(ctx context.Context, w *worker.Worker, o *[]worker.Iface) {
 		fmt.Printf("Worker #1 one tick\n")
 		for i := 0; i < 1000; i++ {
 			select {
@@ -22,9 +22,9 @@ func main() {
 				time.Sleep(1 * time.Millisecond)
 			}
 		}
-	})
+	}, nil)
 
-	w2 := worker.New(func(ctx context.Context, w *worker.Worker) {
+	w2 := worker.New(func(ctx context.Context, w *worker.Worker, o *[]worker.Iface) {
 		fmt.Printf("Worker #2 one tick\n")
 		for i := 0; i < 1000; i++ {
 			select {
@@ -35,14 +35,14 @@ func main() {
 				time.Sleep(1 * time.Millisecond)
 			}
 		}
-	})
+	}, nil)
 
-	_ = worker.New(func(ctx context.Context, w *worker.Worker) {
+	_ = worker.New(func(ctx context.Context, w *worker.Worker, o *[]worker.Iface) {
 		fmt.Printf("Worker #3 one tick\n")
 		time.Sleep(2 * time.Second)
 		fmt.Printf("Worker #3 Exit\n")
 		w.Shutdown(nil)
-	})
+	}, nil)
 
 	time.Sleep(3 * time.Second)
 

+ 7 - 5
worker/worker.go

@@ -11,15 +11,17 @@ type Worker struct {
 	stopped bool
 }
 
-type Callback func(ctx context.Context, w *Worker)
+type Iface interface{}
 
-func New(f Callback) *Worker {
+type Callback func(ctx context.Context, w *Worker, o *[]Iface)
+
+func New(f Callback, o *[]Iface) *Worker {
 	ctx, cancel := context.WithCancel(context.Background())
 	w := Worker{ctx: ctx, cancel: cancel, chDone: make(chan bool)}
-	return (&w).loop(f)
+	return (&w).loop(f, o)
 }
 
-func (this *Worker) loop(f func(ctx context.Context, w *Worker)) *Worker {
+func (this *Worker) loop(f Callback, o *[]Iface) *Worker {
 	go func() {
 		for {
 			select {
@@ -27,7 +29,7 @@ func (this *Worker) loop(f func(ctx context.Context, w *Worker)) *Worker {
 				this.chDone <- true
 				return
 			default:
-				f(this.ctx, this)
+				f(this.ctx, this, o)
 			}
 		}
 	}()