Page Views
    
    
      Posted on 
      
    
  
  
    统计网站的页面浏览次数( Page Views )是分析网站的重要参数之一。由于多个用户发送的请求很可能是同时进行的,所以这里涉及到并发操作时对变量的保护问题。
mutex
在统计页面浏览次数时,我们可以使用一个变量 pageView 来表示页面的浏览次数,并用一个 mutex 锁来保护变量存取。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | var (pageView int
 mutex sync.Mutex
 )
 
 func handler(w http.ResponseWriter, r *http.Request) {
 mutex.Lock()
 pageView++
 mutex.Unlock()
 fmt.Fprintf(w, "<h1>%v</h1>", pageView)
 }
 
 func main() {
 http.HandleFunc("/", handler)
 http.ListenAndServe("localhost:8080", nil)
 }
 
 | 
channel
除了使用互斥锁来保护变量之外,我们来可以使用 golang 中特有的unbuffered channel 来获取页面浏览次数,我们在 main 函数中起一个 goroutine 来生产递增的 nextID ,每个 nextID <- i 发送操作均会阻塞直到一个 goroutine 启动时通过 <-nextID 来接收,这里因为使用了unbuffered channel ,所以保证了整个过程的原子性。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | var nextID = make(chan int)
 func handler(w http.ResponseWriter, r *http.Request) {
 fmt.Fprintf(w, "<h1>%v</h1>", <-nextID)
 }
 
 func main() {
 http.HandleFunc(“/”, handler)
 go func() {
 for i := 0; ; i++ {
 nextID <- i
 }
 }()
 http.ListenAndServe("localhost:8080", nil)
 }
 
 |