channel 分爲無緩衝 channel 和有緩衝 channel。二者的區別以下:mysql
無緩衝:發送和接收動做是同時發生的。若是沒有 goroutine 讀取 channel (<- channel),則發送者 (channel <-) 會一直阻塞。sql
緩衝:緩衝 channel 相似一個有容量的隊列。當隊列滿的時候發送者會阻塞;當隊列空的時候接收者會阻塞。url
package main
//消息隊列 channel
import (
"fmt"
"runtime"
"time"
)
var url_read_mysql_lis = make(chan string, 2000) //必須初始化大小
func write_channel(queue chan string, data string) { //寫入數據
//queue <- data
ok := true
for ok {
select {
case <-time.After(time.Second * 2):
println("write channel timeout")
ok = true
case queue <- data:
//println("write ok")
ok = false
//return 1
}
}
//return 0
}
func read_channel(queue chan string) string { //讀取數據
ok := true
for ok {
select {
case <-time.After(time.Second * 2):
println("read channel timeout")
ok = true
case i := <-queue:
//println(i)
ok = false
return i
}
}
return ""
}
func main() {
fmt.Printf("1111111 ")
//defer close(cs)
write_channel(url_read_mysql_lis, "33333333333333")
//go func() {
// cs <- "qqqqqqqqqqqq"
//}()
//ss := <-url_read_mysql_lis
ss := read_channel(url_read_mysql_lis)
fmt.Println(ss)
for {
time.Sleep(1 * time.Second)
runtime.Gosched()
}
}隊列
package main //消息隊列 channel //BY: 29295842@qq.com import ( "fmt" "runtime" "time" ) var url_read_mysql_lis = make(chan string, 2000) //必須初始化大小 func write_channel(queue chan string, data string) { //寫入數據 //queue <- data ok := true for ok { select { case <-time.After(time.Second * 2): println("write channel timeout") ok = true case queue <- data: //println("write ok") ok = false //return 1 } } //return 0 } func read_channel(queue chan string) string { //讀取數據 ok := true for ok { select { case <-time.After(time.Second * 2): println("read channel timeout") ok = true case i := <-queue: //println(i) ok = false return i } } return"" } func main() { fmt.Printf("1111111 ") //defer close(cs) write_channel(url_read_mysql_lis,"33333333333333") //go func() { //cs <-"qqqqqqqqqqqq" //}() //ss := <-url_read_mysql_lis ss := read_channel(url_read_mysql_lis) fmt.Println(ss) for { time.Sleep(1 * time.Second) runtime.Gosched() } }