|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/http" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | + |
| 9 | + _ "net/http/pprof" // Standard way of adding pprof to your server |
| 10 | +) |
| 11 | + |
| 12 | +func busyWork(d time.Duration) { |
| 13 | + end := time.Now().Add(d) |
| 14 | + for time.Now().Before(end) { |
| 15 | + // Busy loop |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +func gatherClues(wg *sync.WaitGroup) { |
| 20 | + defer wg.Done() |
| 21 | + fmt.Println("Gathering clues...") |
| 22 | + busyWork(500 * time.Millisecond) |
| 23 | +} |
| 24 | + |
| 25 | +func analyzeEvidence(wg *sync.WaitGroup) { |
| 26 | + defer wg.Done() |
| 27 | + fmt.Println("Analyzing evidence...") |
| 28 | + busyWork(1 * time.Second) |
| 29 | +} |
| 30 | + |
| 31 | +func interviewWitnesses(wg *sync.WaitGroup) { |
| 32 | + defer wg.Done() |
| 33 | + fmt.Println("Interviewing witnesses...") |
| 34 | + busyWork(1 * time.Second) |
| 35 | +} |
| 36 | + |
| 37 | +func chaseSuspect(wg *sync.WaitGroup) { |
| 38 | + defer wg.Done() |
| 39 | + fmt.Println("Chasing the suspect...") |
| 40 | + busyWork(2 * time.Second) |
| 41 | +} |
| 42 | + |
| 43 | +func solveMystery(wg *sync.WaitGroup) { |
| 44 | + defer wg.Done() |
| 45 | + fmt.Println("Solving the mystery...") |
| 46 | + busyWork(2 * time.Second) |
| 47 | +} |
| 48 | + |
| 49 | +func main() { |
| 50 | + var wg sync.WaitGroup |
| 51 | + |
| 52 | + // Server for pprof |
| 53 | + go func() { |
| 54 | + fmt.Println(http.ListenAndServe("localhost:6060", nil)) |
| 55 | + }() |
| 56 | + wg.Add(1) // pprof - so we won't exit prematurely |
| 57 | + |
| 58 | + wg.Add(4) // Adding 4 detective tasks |
| 59 | + go gatherClues(&wg) |
| 60 | + go analyzeEvidence(&wg) |
| 61 | + go interviewWitnesses(&wg) |
| 62 | + go chaseSuspect(&wg) |
| 63 | + go solveMystery(&wg) |
| 64 | + |
| 65 | + wg.Wait() // Wait for all detective tasks to complete |
| 66 | + fmt.Println("Mystery solved!") |
| 67 | +} |
0 commit comments