Created
February 23, 2017 04:11
-
-
Save hackintoshrao/b1fbbf47c977d7f7120f8adf44de57e2 to your computer and use it in GitHub Desktop.
Intrumentation to obtain the number of go routine alive in the sytem.
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" | |
| "runtime" | |
| "strconv" | |
| ) | |
| // get the count of number of go routines in the system. | |
| func countGoRoutines() int { | |
| return runtime.NumGoroutine() | |
| } | |
| func getGoroutinesCountHandler(w http.ResponseWriter, r *http.Request) { | |
| // Get the count of number of go routines running. | |
| count := countGoRoutines() | |
| w.Write([]byte(strconv.Itoa(count))) | |
| } | |
| // 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 | |
| http.HandleFunc("/_count", getGoroutinesCountHandler) // 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