A systematic review of Golang knowledge, today summarizes some of the characteristics of the channel and some simple implementation.
Don ' t communicate by sharing memory;share memory by communicating.
1, the channel type itself is concurrency-safe, which is the only type of go that can meet concurrency security.
2, the channel needs to be initialized because it is a reference type, otherwise its value is nil, and any operation on it will be blocked.
3, can be understood as a FIFO queue, even if the blocked objects are in strict order, the channel is empty, a coprocessor fetch data, and then the B process to fetch data, both will block, when the channel has data, will still follow the order of A and B.
4, the receiving and sending operation of the same channel is mutually exclusive, runtime will only perform one channel receiving or sending, not at the same time.
5, for the element in the channel is also, if it is not completed is copied into the channel, then it will never be seen by the receiver.
6, the entry channel is not the element itself, but the copy of the element, and this operation is not fragmented, that is, the copy into the channel, but the original object has not been deleted.
7, ibid, the data will not be removed when the elements in the channel is not deleted.
8, the operation that is sent is blocked until the copied element is placed in the channel with the copied copy.
9, the channel blocking mechanism is to implement the mutex of the operation and the completion of the element.
10, the buffer channel element is full, receive and send will block, but the order of receiving and sending after recovery is absolutely fair, not chaotic. For non-buffered channels, the first is blocked, the producers and consumers at the same time docking, blocking will be lifted.
11, it can be understood that the non-buffered channel is synchronous transmission, the buffer channel is asynchronous transmission.
12, the case of panic: operation on the closed channel, closing the closed channel;
13, the element is passed in the channel is a shallow copy.
It is best not to close the channel from the receiver of the channel, but to close the channel from the sender of the channel
Package Mainimport "FMT" Func Main () {chx: = make (chan int, 2)//Sender Go-func () {for I: = 0 ; I < 10; i++ {fmt. Printf ("sender:sending element%v...\n", i) Chx <-i} fmt. Println ("Sender:close the Channel ...") Close (CHX)} ()//receiver for {elem, OK: = <-chx If!ok {fmt. PRINTLN ("receiver:closed channel") Break} FMT. Printf ("receiver:received an element:%v\n", Elem)} fmt. Println ("End.")}