package main
import (
"fmt"
"sync"
"time"
)
func main() {
// ============== channel ==============
startTime2 := time.Now()
testChannel()
endTime2 := time.Now()
fmt.Printf("======> Done! use time: %f",(endTime2.Sub(startTime2).Seconds()))
fmt.Println()
}
// 使用 channel 信道,可以在协程之间传递消息。等待并发协程返回消息。
var ch = make(chan string, 10) // 创建大小 10 的缓存通道
func testChannel() {
for i := 0; i 3; i++ {
go downloadV2("a.com/" + string(i+'0'))
}
for i := 0; i 3; i++ {
msg := ch // 等待信道返回消息。
fmt.Println("finish", msg)
}
}
// ================= 工具 V =================
func downloadV2(url string) {
fmt.Println("start to download", url)
time.Sleep(time.Second)
ch url // 将 url 发送给信道
}
ch1 := make(chan int) // 创建一个整型类型的通道
ch2 := make(chan interface{}) // 创建一个空接口类型的通道, 可以存放任意格式
type Equip struct{ /* 一些字段 */ }
ch2 := make(chan *Equip) // 创建Equip指针类型的通道, 可以存放*Equip
// 创建一个空接口通道
ch := make(chan interface{})
// 将0放入通道中
ch 0
// 将hello字符串放入通道中
ch "hello"
package main
func main() {
// 创建一个整型通道
ch := make(chan int)
// 尝试将0通过通道发送
ch 0
}
package main
import (
"fmt"
)
func main() {
// 构建一个通道
ch := make(chan int)
// 开启一个并发匿名函数
go func() {
fmt.Println("start goroutine")
// 通过通道通知main的goroutine
ch 0
fmt.Println("exit goroutine")
}()
fmt.Println("wait goroutine")
// 等待匿名goroutine
ch
fmt.Println("all done")
}
// 输出如下:
// wait goroutine
// start goroutine
// exit goroutine
// all done
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/4729/viewspace-2797138/,如需转载,请注明出处,否则将追究法律责任。