学习笔记,写到哪是哪。
chan类似于java和python里面queue的使用,注意是线程安全的,自带锁。总结一下使用口诀,初始化需要make,chan在前为发送,chan在后为接受。
样例代码如下
package main import "fmt" func send(ch chan int) { for i := 0; i <= 5; i++ { ch <- i fmt.Printf("send %d to channel\n", i) } } func receive(ch chan int) { for data := range ch { fmt.Printf("receive %d \n", data) if data == 5 { fmt.Println("end") break } } } func main() { ch := make(chan int) go send(ch) receive(ch) close(ch) }
执行结果
send 0 to channel
receive 0
receive 1
send 1 to channel
send 2 to channel
receive 2
receive 3
send 3 to channel
send 4 to channel
receive 4
receive 5
end
小结
感觉会在以后的项目中频繁使用,毕竟队列化在多任务调度是非常常见的手段,