go channel
Posted shhnwangjian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go channel相关的知识,希望对你有一定的参考价值。
go channel
1、不同goroutine之间如何进行通讯?
- 全局变量和锁同步
- Channel
2、channel概念
- 类似unix中管道(pipe)
- 先进先出
- 线程安全,多个goroutine同时访问,不需要加锁
- channel是有类型的,一个整数的channel只能存放整数
3、channel声明
var 变量名 chan 类型
var test chan int var test chan string var test chan map[string]string var test chan stu var test chan *stu
4、channel初始化
使用make进行初始化
var test chan int test = make(chan int, 10) var test chan string test = make(chan string, 10)
5、channel基本操作
- 从channel读取数据
var testChan chan int testChan = make(chan int, 10) var a int a = <- testChan
- 从channel写入数据
var testChan chan int testChan = make(chan int, 10) var a int = 10 testChan <- a
channel初始化、基本操作示例:
package main import "fmt" type student struct { name string } func testmap(){ var mapChan chan map[string]string mapChan = make(chan map[string]string, 10) m := make(map[string]string, 16) m["stu01"] = "123" m["stu02"] = "456" mapChan <- m } func teststruct(){ var structChan chan student structChan = make(chan student, 10) stu := student { name: "stu01", } structChan <- stu } func teststruct1(){ var structChan chan *student structChan = make(chan *student, 10) stu := student { name: "stu01", } structChan <- &stu } func main() { var stuChan chan interface{} stuChan = make(chan interface{}, 10) stu := student{name: "stu01"} stuChan <- &stu var stu01 interface{} stu01 = <-stuChan var stu02 *student stu02, ok := stu01.(*student) if !ok { fmt.Println("can not convert") return } fmt.Println(stu02) }
goroutine和channel相结合示例
package main import ( "fmt" "time" ) func write(ch chan int) { for i := 0; i < 100; i++ { ch <- i fmt.Println("put data:", i) } } func read(ch chan int) { for { var b int b = <-ch fmt.Println("get data:", b) time.Sleep(time.Second) } } func main() { intChan := make(chan int, 10) go write(intChan) go read(intChan) time.Sleep(100 * time.Second) }
6、channel特点
- channel阻塞
- 带缓冲区的channel
如下所示,testChan只能放一个元素:
var testChan chan int testChan = make(chan int) var a int a = <- testChan
如下所示,testChan是带缓冲区的chan,一次可以放10个元素:
var testChan chan int testChan = make(chan int, 10) var a int = 10 testChan <- a
以上是关于go channel的主要内容,如果未能解决你的问题,请参考以下文章