Created
September 5, 2020 15:36
-
-
Save adityathebe/253dd9c044114fb9722f9889c8cad774 to your computer and use it in GitHub Desktop.
Go Program in response to : https://medium.com/@qianfg/why-do-we-need-this-2-tier-channel-thing-instead-of-just-have-multiple-worker-goroutines-read-from-d29559042a33
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" | |
"net/http" | |
) | |
func handler(w http.ResponseWriter, r *http.Request) { | |
query := r.URL.Query() | |
name := query.Get("name") | |
fmt.Println("Query", name) | |
// Pass it to the worker | |
jobQueue <- name | |
// Send response | |
fmt.Fprintf(w, "Hello %s", name) | |
} |
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 "net/http" | |
var jobQueue chan string | |
func main() { | |
jobQueue = make(chan string) | |
worker := Worker{maxWorkers: 2} | |
worker.start() | |
http.HandleFunc("/", handler) | |
http.ListenAndServe(":8000", nil) | |
} |
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 doWork(val string) string { | |
fmt.Println("Worker", val) | |
time.Sleep(10 * time.Second) | |
return val | |
} | |
// Worker listens to the jobQueue Channel | |
type Worker struct { | |
maxWorkers int | |
} | |
func (w Worker) start() { | |
for i := 0; i < w.maxWorkers; i++ { | |
go func() { | |
fmt.Println("Coroutine Running ...") | |
for x := range jobQueue { | |
x := doWork(x) | |
fmt.Println("Result", x) | |
} | |
}() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment