github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume3/section5/gopherface/common/asyncq/asyncq.go (about) 1 package asyncq 2 3 import ( 4 "log" 5 ) 6 7 var TaskQueue chan Task 8 var TaskWorkerQueue chan chan Task 9 10 type TaskWorker struct { 11 ID int 12 TaskChannel chan Task 13 TaskWorkerQueue chan chan Task 14 } 15 16 func NewTaskWorker(id int, taskWorkerQueue chan chan Task) TaskWorker { 17 taskWorker := TaskWorker{ 18 ID: id, 19 TaskChannel: make(chan Task), 20 TaskWorkerQueue: taskWorkerQueue, 21 } 22 23 return taskWorker 24 } 25 26 func (t *TaskWorker) Start() { 27 go func() { 28 for { 29 t.TaskWorkerQueue <- t.TaskChannel 30 31 select { 32 case task := <-t.TaskChannel: 33 log.Printf("Asynchronous task worker #%d is performing a task.\n", t.ID) 34 task.Perform() 35 36 } 37 } 38 }() 39 } 40 41 func StartTaskDispatcher(taskWorkerSize int) { 42 43 TaskWorkerQueue = make(chan chan Task, taskWorkerSize) 44 45 for i := 0; i < taskWorkerSize; i++ { 46 log.Print("Starting asynchronous task worker #", i+1) 47 taskWorker := NewTaskWorker(i+1, TaskWorkerQueue) 48 taskWorker.Start() 49 } 50 51 go func() { 52 for { 53 select { 54 case task := <-TaskQueue: 55 go func() { 56 taskChannel := <-TaskWorkerQueue 57 taskChannel <- task 58 }() 59 } 60 } 61 }() 62 } 63 64 func init() { 65 66 TaskQueue = make(chan Task, 108) 67 68 }