美文网首页
Go Hello world

Go Hello world

作者: dongshixiao | 来源:发表于2018-05-14 11:48 被阅读0次

GO:
学一门语言,肯定要先去学习怎么打印 hello world 。
网络版:

package main

import (
    "net/http"
    "fmt"
)

func main() {

    http.HandleFunc("/", func(
        writer http.ResponseWriter,
        request *http.Request) {

            fmt.Fprintf(writer,"<h1>hello world %s</h1>",request.FormValue("name"))
    })

    http.ListenAndServe(":8888",nil)
}

运行之后浏览器访问


hello world网络版

Hello world 并行版:

package main

import (
    "fmt"
    "time"
)

func main()  {
    for i:=0; i<500; i++ {
        // go starts a goroutine
        go printHelloWorld(i)
    }

    time.Sleep(time.Millisecond)
}

func printHelloWorld(i int)  {
    fmt.Printf("hello world %d \n" ,i)
}

运行后效果:

hello world并行版

使用chan的并行版本

package main

import (
    "fmt"
)

func main() {
    ch := make(chan string)
    for i := 0; i < 5000; i++ {
        // go starts a goroutine
        go printHelloWorld(i, ch)
    }

    for {
        msg := <-ch
        fmt.Println(msg)
    }

}

func printHelloWorld(i int, ch chan string) {
    for {
        ch <- fmt.Sprintf("hello world %d \n", i)
    }
}

需要手动结束,死循环。

相关文章

网友评论

      本文标题:Go Hello world

      本文链接:https://www.haomeiwen.com/subject/swmddftx.html