Skip to content

Instantly share code, notes, and snippets.

@CMingTseng
Forked from KScaesar/gopl_ch1_server2.go
Created September 10, 2018 18:03
Show Gist options
  • Save CMingTseng/2d95b226fcc14e135d93c1961f47e24b to your computer and use it in GitHub Desktop.
Save CMingTseng/2d95b226fcc14e135d93c1961f47e24b to your computer and use it in GitHub Desktop.
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