commit 83f216a3519463cff36b50442f305e4b30b2b691 Author: almondaja Date: Mon Sep 29 11:50:23 2025 +0700 initial commit diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..3903110 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module 5803024017/routine-test + +go 1.25.1 diff --git a/main.go b/main.go new file mode 100644 index 0000000..2ba014e --- /dev/null +++ b/main.go @@ -0,0 +1,50 @@ +package main + +import ( + "fmt" + "math/rand" + "sync" + "time" +) + +const ( + numWorkers = 10 + numJobs = 1000 +) + +// Simulate processing a request +func handleRequest(workerID, jobID int) { + fmt.Printf("Worker %d handling request %d\n", workerID, jobID) + // Simulate random processing time + time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) +} + +func worker(id int, jobs <-chan int, wg *sync.WaitGroup) { + for job := range jobs { + handleRequest(id, job) + wg.Done() + } +} + +func main() { + rand.Seed(time.Now().UnixNano()) // Seed random number generator + + jobs := make(chan int, numJobs) + var wg sync.WaitGroup + + // Start 10 worker goroutines + for w := 1; w <= numWorkers; w++ { + go worker(w, jobs, &wg) + } + + // Send 1,000 jobs to the workers + for j := 1; j <= numJobs; j++ { + wg.Add(1) + jobs <- j + } + + close(jobs) // No more jobs to send + + wg.Wait() // Wait for all jobs to complete + fmt.Println("All requests processed.") +}