The Go channel is synchronized

GoroutineA can execute the code by obtaining the channel permission. After the execution, the channel will be marked as passable. GB can only obtain the channel and execute the code block. In the real business scenario, we go to the toilet on the train. Once there is someone in the toilet, the warning light will show that there is someone inside, so I don’t have to wait at the door. I can do other things, such as playing with my mobile phone. What are the go leaders doing with this approach, and I wonder if it’s to save resources and implement AIO as a threading model?

Channel implementation comes in two ways

1. Cache can be set

var c = make(chan int.10)
var a string

func f(a) {
	a = "hello, world"
	c <- 0
}

func main(a) {
	go f()
	<-c
	print(a)
}
Copy the code

10 in c means the cache size is 10.

2. Do not set cache

var c = make(chan int)
var a string

func f(a) {
	a = "hello, world"
	<-c
}

func main(a) {
	go f()
	c <- 0
	print(a)
}
Copy the code

If the channel is not cached, the data cannot be cached locally. When the channel permission is obtained, the value 0 is sent directly to the channel after executing the specified code.

The cache channel serves another purpose:

var limit = make(chan int.3)

func main(a) {
	for _, w := range work {
		go func(w func(a)) {
			limit <- 1
			w()
			<-limit
		}(w)
	}
	select{}}Copy the code

When the channel cache capacity is set to 3, it indicates that the channel can be accessed by three Gs at the same time, that is, three Gs can execute the specified code block at the same time.

The concept of the passage can be found everywhere in our life, the big guy’s inspiration comes from life, and higher than life.