Go Programming Language book example server2 有错吗?

问题描述 投票:0回答:1

我正在阅读 The Go programming Language Book。在第 1 章中,服务器 2 示例:Book 的代码 互斥锁用于防止竞争条件。但是我复制了代码并尝试运行它,但结果不一致。示例中的代码是否错误?

这是我使用代码的方式:

server.go

package server

import (
    "fmt"
    "log"
    "net/http"
    "sync"
)

const (
    PORT string = ":8000"
)

var count int

var mu sync.Mutex

func Run() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/count", counter)
    fmt.Printf("Server is listening on port: %s\n", PORT)
    log.Fatal(http.ListenAndServe(PORT, nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
    mu.Lock()
    count++
    mu.Unlock()
    fmt.Fprintf(w, "URL Path = %q\n", r.URL.Path)
}

func counter(w http.ResponseWriter, r *http.Request) {
    mu.Lock()
    fmt.Fprintf(w, "Count = %d\n", count)
    mu.Unlock()
}

main.go

package main

import "book/server"

func main() {
    server.Run()
}

当我运行:go run main.go 并访问两个页面 localhost:8000 和 localhost:8000/count

  1. 每当我刷新 /count 页面时,计数都会增加。为什么?
  2. 每当我刷新 / 和 /count 页面时,显示的计数都会不一致地增加?不是按照刷新次数。为什么?

我原以为只有当我访问 / 页面而不是 /count 页面时,计数才会增加,并且它会根据我的刷新次数增加。

go concurrency webserver mutex error-correction
1个回答
0
投票

那是因为当你用浏览器测试网页时,大多数时候,浏览器也会向

http://localhost:8000/favicon.ico
发送请求。请看下面的截图:

/favicon.ico
没有专门的处理程序,它匹配
/
,所以由
server.handler
处理。

建议使用其他工具测试此类demo。例如,

curl

$ curl 'http://localhost:8000/'
$ curl 'http://localhost:8000/count'
© www.soinside.com 2019 - 2024. All rights reserved.