Google资深工程师深度讲解Go语言-channel 通道 (十)
【摘要】
一.channel
channelbuffered channelrange.由发送方结束发送理论基础:communication sequential process(csp)不要通过共享内存来通信;通过通信来共享内存
package main import ( "fmt" "time") func chanDemo() { c :...
一.channel
- channel
- buffered channel
- range.由发送方结束发送
- 理论基础:communication sequential process(csp)
- 不要通过共享内存来通信;通过通信来共享内存
-
package main
-
-
import (
-
"fmt"
-
"time"
-
)
-
-
func chanDemo() {
-
c := make(chan int)
-
go func() {
-
for {
-
n := <-c
-
fmt.Println(n)
-
//Output:
-
// 1
-
//2
-
}
-
}()
-
c <- 1
-
c <- 2
-
time.Sleep(time.Microsecond)
-
}
-
-
func main() {
-
chanDemo()
-
}
-
package main
-
-
import (
-
"fmt"
-
"time"
-
)
-
-
func worker(id int, c chan int) {
-
for n := range c {
-
//n := <-c //收数据
-
//n, ok := <-c
-
//if !ok {
-
// break
-
//}
-
-
fmt.Printf("worker %d received %d\n", id, n)
-
-
//fmt.Println(n)
-
//Output:
-
// 1
-
//2
-
}
-
-
}
-
func createWorker(id int, ) chan<- int { //返回channel
-
c := make(chan int)
-
go worker(id, c)
-
return c
-
}
-
func chanDemo() {
-
//var c chan int //变量c 是个chanel 里面内容是int
-
//c := make(chan int)
-
-
var channels [10]chan<- int
-
for i := 0; i < 10; i++ {
-
channels[i] = createWorker(i)
-
}
-
-
for i := 0; i < 10; i++ {
-
channels[i] <- 'a' + i
-
}
-
for i := 0; i < 10; i++ {
-
channels[i] <- 'A' + i
-
}
-
-
//c <- 1 //发数据
-
//c <- 2
-
time.Sleep(time.Microsecond)
-
}
-
-
func bufferedChannel() {
-
c := make(chan int, 3)
-
go worker(0, c)
-
c <- 'a'
-
c <- 'b'
-
c <- 'c'
-
c <- 'd'
-
time.Sleep(time.Microsecond)
-
}
-
func channelClose() { //发送方通知接收方
-
c := make(chan int, 3)
-
go worker(0, c)
-
c <- 'a'
-
c <- 'b'
-
c <- 'c'
-
c <- 'd'
-
close(c)
-
time.Sleep(time.Microsecond)
-
}
-
func main() {
-
fmt.Println("channel ad first-class citizen")
-
chanDemo()
-
-
fmt.Println("Buffered channel")
-
bufferedChannel()
-
-
fmt.Println("Channel close and range")
-
channelClose()
-
}
二.传统同步机制
- waitGroup :等待组
- Mutex 互斥
- Cond
-
package main
-
-
import (
-
"fmt"
-
"sync"
-
"time"
-
)
-
-
type atomicInt struct {
-
value int
-
lock sync.Mutex
-
}
-
-
func (a *atomicInt)increment() {
-
a.lock.Lock()
-
defer a.lock.Unlock()
-
a.value++
-
}
-
-
func (a *atomicInt)get()int {
-
a.lock.Lock()
-
defer a.lock.Unlock()
-
return a.value
-
}
-
-
func main() {
-
var a atomicInt
-
a.increment()
-
go func() {
-
a.increment()
-
}()
-
time.Sleep(time.Second)
-
fmt.Println(a.get())
-
}
文章来源: blog.csdn.net,作者:lxw1844912514,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/lxw1844912514/article/details/108448296
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)