initial commit
This commit is contained in:
commit
83f216a351
50
main.go
Normal file
50
main.go
Normal file
@ -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.")
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user