worker is launched as a goroutine to process work from the buffered channel.
(tasks chan string, worker int)
| 52 | // worker is launched as a goroutine to process work from |
| 53 | // the buffered channel. |
| 54 | func worker(tasks chan string, worker int) { |
| 55 | // Report that we just returned. |
| 56 | defer wg.Done() |
| 57 | |
| 58 | for { |
| 59 | // Wait for work to be assigned. |
| 60 | task, ok := <-tasks |
| 61 | if !ok { |
| 62 | // This means the channel is empty and closed. |
| 63 | fmt.Printf("Worker: %d : Shutting Down\n", worker) |
| 64 | return |
| 65 | } |
| 66 | |
| 67 | // Display we are starting the work. |
| 68 | fmt.Printf("Worker: %d : Started %s\n", worker, task) |
| 69 | |
| 70 | // Randomly wait to simulate work time. |
| 71 | sleep := rand.Int63n(100) |
| 72 | time.Sleep(time.Duration(sleep) * time.Millisecond) |
| 73 | |
| 74 | // Display we finished the work. |
| 75 | fmt.Printf("Worker: %d : Completed %s\n", worker, task) |
| 76 | } |
| 77 | } |