Created
September 2, 2022 15:15
-
-
Save abdulrahmanAlotaibi/7dcd85bc3c1a0db58988420bcb966bb4 to your computer and use it in GitHub Desktop.
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 ( | |
"fmt" | |
"time" | |
) | |
func worker(id int , jobs <- chan int, results chan <- int ){ | |
for j:= range jobs { | |
fmt.Println("Worker: ", id, " started job" ) | |
time.Sleep(time.Second) | |
fmt.Println("Worker: ", id, " has finished job", j) | |
results <- j * 2 | |
} | |
} | |
func main() { | |
numJobs := 10 | |
jobs := make(chan int , numJobs) | |
results := make(chan int , numJobs) | |
for w:= 0 ; w < 3; w++ { | |
go worker(w, jobs, results) | |
} | |
for j:= 0; j < numJobs ; j++ { | |
jobs <- j | |
} | |
close(jobs) | |
fmt.Println("===================================") | |
fmt.Print("Result after processing jobs:") | |
/* | |
To explain the background of the problem: The range operator reads from the channel until the channel is closed. So in the original code, the for-range loop keeps waiting for more input from the channel, and wg.Wait() is never reached. Suneil’s solution separates reading the channel from waiting for the workers to finish. | |
*/ | |
for res:= range results { | |
if res == 18 { | |
fmt.Println("Reached the end", res) | |
close (results) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment