Created
May 9, 2024 06:33
-
-
Save fahadsiddiqui/1c6f3391559149db894fc76155c793d3 to your computer and use it in GitHub Desktop.
Go routines, channels and wait group demo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
type Report struct { | |
Type string `json:"type"` | |
StartTime string `json:"start_time"` | |
EndTime string `json:"end_time"` | |
TotalRecords int `json:"num_of_records"` | |
RecordsWithCoordinates int `json:"records_with_coordinates"` | |
} | |
func Random() *rand.Rand { | |
return rand.New(rand.NewSource(time.Now().UnixNano())) | |
} | |
func Execute(typeOfReport string, r chan Report) { | |
rSecs := Random().Intn(10) | |
log.Printf("Executing report %s and waiting for %d seconds...", typeOfReport, rSecs) | |
time.Sleep(time.Duration(rSecs) * time.Second) | |
report := Report{ | |
Type: typeOfReport, | |
StartTime: "2020-01-01T00:00:00Z", | |
EndTime: "2020-01-01T00:00:00Z", | |
TotalRecords: Random().Intn(100), | |
RecordsWithCoordinates: Random().Intn(50), | |
} | |
r <- report | |
} | |
func main() { | |
log.Println("Starting the program...") | |
r := make(chan Report) | |
var wg sync.WaitGroup | |
wg.Add(3) | |
scrapers := []string{"ScienceDaily", "CNN", "BBC"} | |
for _, s := range scrapers { | |
go func(s string) { | |
log.Printf("Starting report %s...", s) | |
Execute(s, r) | |
wg.Done() | |
}(s) | |
} | |
for i := 0; i < 3; i++ { | |
report := <-r | |
log.Printf("Report %s has been executed...", report.Type) | |
log.Printf("Results for report %s: %v", report.Type, report) | |
} | |
wg.Wait() | |
close(r) | |
log.Println("End of the program") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment