Created
February 23, 2017 03:05
-
-
Save hackintoshrao/b4eb3d89fd1e48a1332b60574f8d6618 to your computer and use it in GitHub Desktop.
Demo of writing into a channel without reading from it.
This file contains hidden or 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" | |
| "log" | |
| "net/http" | |
| "strconv" | |
| ) | |
| // function to add an array of numbers. | |
| func sum(s []int, c chan int) { | |
| sum := 0 | |
| for _, v := range s { | |
| sum += v | |
| } | |
| // writes the sum to the go routines. | |
| c <- sum // send sum to c | |
| } | |
| // HTTP handler for /sum | |
| func sumConcurrent(w http.ResponseWriter, r *http.Request) { | |
| s := []int{7, 2, 8, -9, 4, 0} | |
| c1 := make(chan int) | |
| c2 := make(chan int) | |
| // spin up a goroutine. | |
| go sum(s[:len(s)/2], c1) | |
| // spin up a goroutine. | |
| go sum(s[len(s)/2:], c2) | |
| // not reading from c2. | |
| // go routine writing to c2 will be blocked. | |
| x := <-c1 | |
| // write the response. | |
| fmt.Fprintf(w, strconv.Itoa(x)) | |
| } | |
| func main() { | |
| http.HandleFunc("/sum", sumConcurrent) // set router | |
| err := http.ListenAndServe(":8001", nil) // set listen port | |
| if err != nil { | |
| log.Fatal("ListenAndServe: ", err) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment