Last active
September 10, 2018 18:03
-
-
Save KScaesar/81f116ba477a4d5fcc8cf5a24c3b90d9 to your computer and use it in GitHub Desktop.
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" | |
| "net/http" | |
| "sync" | |
| ) | |
| var mu sync.Mutex | |
| var count int | |
| func main() { | |
| http.HandleFunc("/", hander) | |
| http.HandleFunc("/count", counter) | |
| http.ListenAndServe("localhost:8000", nil) | |
| } | |
| func hander(w http.ResponseWriter, r *http.Request) { | |
| //可以理解避免資源競爭,所以count要用互斥鎖保護 | |
| mu.Lock() | |
| count++ | |
| mu.Unlock() | |
| fmt.Fprintf(w, "count=%d URL.Path=%q \n", count, r.URL.Path) | |
| } | |
| func counter(w http.ResponseWriter, r *http.Request) { | |
| mu.Lock() | |
| fmt.Fprintf(w, "count=%d\n", count) | |
| //為什麼要加互斥鎖 | |
| mu.Unlock() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment