大家好,又见面了,我是全栈君。
一.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())
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/111707.html原文链接:https://javaforall.net