首页  

go程序设计语言01_06入门之并发获取多个URL     所属分类 go 浏览量 903
并发编程
goroutine  channel
goroutine  函数的并发执行方式
channel 用来在goroutine之间进行参数传递
main函数本身也运行在一个goroutine中
go functionxxx  创建一个新的goroutine,并在这个新的goroutine中执行这个函数
make函数创建了一个传递string类型参数的channel

当一个goroutine尝试在一个channel上做send或者receive操作时
这个goroutine会阻塞在调用处,直到另一个goroutine从这个channel里接收或者写入值
每一个fetch函数在执行时都会往channel里发送一个值(ch <- expression),主函数负责接收这些值(<-ch)

在main函数里接收所有fetch函数传回的字符串 




fetchall.go // Fetchall fetches URLs in parallel and reports their times and sizes. package main import ( "fmt" "io" "io/ioutil" "net/http" "os" "time" ) func main() { start := time.Now() ch := make(chan string) for _, url := range os.Args[1:] { go fetch(url, ch) // start a goroutine } for range os.Args[1:] { fmt.Println(<-ch) // receive from channel ch } fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds()) } func fetch(url string, ch chan<- string) { start := time.Now() resp, err := http.Get(url) if err != nil { ch <- fmt.Sprint(err) // send to channel ch return } nbytes, err := io.Copy(ioutil.Discard, resp.Body) resp.Body.Close() // don't leak resources if err != nil { ch <- fmt.Sprintf("while reading %s: %v", url, err) return } secs := time.Since(start).Seconds() ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url) }
go build fetchall.go ./fetchall http://codefun007.xyz http://codefun007.xyz/about.htm http://codefun007.xyz/links.htm 0.12s 933 http://codefun007.xyz/about.htm 0.14s 1562 http://codefun007.xyz/links.htm 0.14s 4981 http://codefun007.xyz 0.14s elapsed

上一篇     下一篇
Brew 简介及安装

国货飞跃

go程序设计语言01_05入门之获取URL

GO箴言 goproverbs

简洁的GO语言

GO多线程异步处理实例