go的channel

go language channel

go to goroutine language provides concurrency, go to the language also provides a channel for communication between concurrent events.
Traditional programming languages through shared memory communication, when multiple threads at the same time operating a shared variable, in order to make the program achieve the intended purpose, might be a locked variable, which would make the concurrent program wait, causing local program serial. The design concept of the channel is to go through the shared memory communication. is a special type of channel, which follows the FIFO principle, to ensure the order of the data transceiver. goroutine go language may communicate by channel.

chan's statement

import "fmt"

func main() {

	var chan1 chan int // 声明int类型的chan

	// chan是引用类型,必须舒适化后才能使用
	chan1 = make(chan int, 10)
	fmt.Println(chan1) // 0xc000082000
}

chan's statement One thing to note, that chan must be used in order to make use of initialization

chan operations

package main

import "fmt"

func main() {

	var chan1 chan int // 声明int类型的chan

	// chan是引用类型,必须舒适化后才能使用
	chan1 = make(chan int, 10)

	// 向chan中传入10
	chan1 <- 10

	// 从chan中取值
	x := <-chan1
	fmt.Println(x)

	// 关闭chan
	close(chan1)

}

chan If you are using must also have a buffer
when chan data stored inside the buffer is full, in other goroutine want to have to wait for data transmission chan chan vacant position, so when the time needed to create a reasonable chan the buffer giving chan

And a chan goroutine plurality of operation for the loop chan

package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup

var chan1 chan interface{}

func add_to_chan(c chan interface{}, i int) {
	c <- i
	wg.Done()
}

func main() {

	// 过个goroutine往chan里添加数据
	chan1 = make(chan interface{}, 200)
	for i := 1; i < 100; i++ {
		wg.Add(1)
		go add_to_chan(chan1, i)
	}

	wg.Wait()

	defer close(chan1)
	// chan的for循环
	for i := range chan1 {
		fmt.Println(i)
	}

}

Guess you like

Origin www.cnblogs.com/ivy-blogs/p/12659430.html