大家好,又见面了,我是全栈君。
一.channel
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()
}
二.传统同步机制
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.cn/111707.html原文链接:https://javaforall.cn