大家好,又见面了,我是全栈君。
一.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())
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/111707.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...