go语言入门[3]—-并发&线程通讯

go语言的的多线程是通过“goroutine”来实现的,通过“go”关键字新建一个goroutine
比如:

    go hello()

其实,goroutine比线程更小,“十几个goroutine可能体现在底层也就五六个线程”,且是内存共享的

不同的goroutine之间,通过channel来通讯,比如下面的的程序,主线程是一个http sever,收到http请求后,将url塞入channel,然后下面的“see”函数在来处理这个channel

package main
 
import (
	"fmt"
    "net/http"
)
//定义一个channel
var cc chan string
 
func main() {
    fmt.Println("--ubox-event--start--")
 
    //新建一个channel	
    cc = make(chan string)
    //使用一个goroutine启动see函数,编号为1
    go see("1")
    //启动httpServe
    http.HandleFunc("/*", httpServe)
    http.ListenAndServe(":8008", nil)
}
 
func httpServe(w http.ResponseWriter, req *http.Request) {
    url := req.URL.String()
    w.Write([]byte("Hello"))
    //将url塞入channel
    cc <- url
}
 
func see(n string) {
    fmt.Println("--see--" + n + "--start--")
    //通过range参数取出channel,每当上面httpServe被塞入一次,这里即执行一次
    for s := range cc {
        fmt.Println("--see--url-" + n + "-" + s)
    }
}

go run 启动上面的程序,然后访问localhost:8008/xxxxx,便会看到 “–see–url-1-/xxxxx”

有意思的是 ,如果你在上面再启动两个goroutine,即go see(“2″),go see(“3″)

然后不断访问localhost:8008/xxxxx,打印出来的并不一直是 “url-1”,而是 url-1、url-2、url-3轮流出现,且每次访问只出现一次,也就是说channel并不会一直分配给第一个range

3 Comments

  • 2013 年 07 月 20 日 - 上午 8:29 | Permalink

    巧了,顺藤摸瓜进来了!

  • 2013 年 07 月 24 日 - 上午 4:24 | Permalink

    谢谢博主分享!

  • 2013 年 09 月 23 日 - 上午 8:50 | Permalink

    能坚持写博客,至少也是个有恒心的人,赞一个
    癸巳年(蛇)八月十九 2013-9-23

  • 包包网 进行回复 取消回复

    电子邮件地址不会被公开。 必填项已用 * 标注

    *

    *