Google资深工程师深度讲解Go语言-channel 通道 (十)

一.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())
}

 

posted @ 2020-09-07 16:52  码农编程进阶笔记  阅读(58)  评论(0编辑  收藏  举报
返回顶部 有事您Q我