Windows中的行为不稳定?

  Update:  The question title can be misleading.  This was not Go's fault at all.

See the first comment or the accepted answer.

下面的代码(几乎相同)在Linux下可以计算页面浏览量,但在Windows下可以将页面浏览量提高一倍。

有人能弄清楚为什么吗?

package main

import (

"fmt"

"http"

)

func main() {

println("Running")

http.HandleFunc("/", makeHomeHandler())

http.ListenAndServe(":8080", nil)

}

// this version compiles and run OK under the Linux version of Golang

func makeHomeHandler() func(c *http.Conn, r *http.Request) {

views := 1

return func(c *http.Conn, r *http.Request) {

fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views)

views++

}

}

/*

// this version compiles and run OK under the mingw version of Golang

// it uses a different argument type for the handler function,

// but the counter says "1 so far", then "3 so far", "5 so far", and so on.

func makeHomeHandler() func(c http.ResponseWriter, r *http.Request) {

views := 1

return func(c http.ResponseWriter, r *http.Request) {

fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views)

views++

}

}

*/

在Mingw下:

http://localhost:8080/monkeys => Counting monkeys, 1 so far.

http://localhost:8080/monkeys => Counting monkeys, 3 so far.

http://localhost:8080/donkeys => Counting donkeys, 5 so far.

这可能是错误吗?

跟进:

实际上,如果我为另一个页面定义了其他处理程序,例如:

   http.HandleFunc("/test", testPageHandler)

Wich没有闭包,也没有增加任何东西,计数器无论如何都会增加,但是只有+1:

因此,仍然在Mingw的领导下:

http://localhost:8080/monkeys => Counting monkeys, 1 so far.

http://localhost:8080/monkeys => Counting monkeys, 3 so far.

http://localhost:8080/test => Another handler function that does not increment "views"

http://localhost:8080/donkeys => Counting donkeys, 6 so far.

在Linux下,输出如下所示:

http://localhost:8080/monkeys => Counting monkeys, 1 so far.

http://localhost:8080/monkeys => Counting monkeys, 2 so far.

http://localhost:8080/test => Another handler function that does not increment "views"

http://localhost:8080/donkeys => Counting donkeys, 3 so far.

回答:

我怀疑您看到的行为是由于浏览器为您的页面请求图标,而不是由于Windows / mingw。如果您想知道,我在达尔文使用6g,我的Firefox

3.6也可以在Mac OS X上运行。

为了强调我的怀疑,请尝试将以下内容添加到处理程序函数中:

fmt.Printf("Counting %s, %d so far.\n", r.URL.Path[1:], views)

然后,您可以看到所有到达您的应用程序的请求。刚启动的Firefox对URL http:// localhost:8080 /

chuchichaestli的一个请求产生了以下输出:

Counting chuchichaestli, 1 so far.

Counting favicon.ico, 2 so far.

因为Firefox还会为您的go页面请求图标。

此外,views即使可能存在多个并发请求,您也不会锁定/同步访问。

以上是 Windows中的行为不稳定? 的全部内容, 来源链接: utcz.com/qa/404828.html

回到顶部