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() } }