SoFunction
Updated on 2025-03-04

Analysis of golang channel pipeline usage example

Define channel pipeline

When defining a channel, you also need to define the value type sent to the pipeline. The channel can be created using the built-in make() function:

var ch = make(chan int) //Equivalent to: make(chan Type, 0)var ch = make(chan Type,capacity)

Channel pipe plug value and take value

ch <- 666  //Put 666 into the ch pipe<- ch  // Receive the value to the ch pipeline and discard itx := <-ch  //Receive data from the ch pipeline and copy it to xx, ok := <-ch  //Receive data from the ch pipeline and copy it to x, and check whether the channel is closed or empty

When capacity=0, the channel pipeline is read and write without buffering.
When capacity>0, the channel pipeline has buffers, which are non-blocking, and the write is not blocked until the capacity elements are full.
 

Note: By default, the channel receives and sends data both blocked unless the other end is ready, which makes goroutine synchronization easier without the need for displayed locks.

Synchronization is achieved through channel pipeline and data interaction

package main
import (
	"fmt"
	"time"
)
func main() {
	//Create channel	ch := make(chan string)
	defer ("The main coroutine is also over")
	go func() {
		defer ("Subcorrelation call completed")
		for i := 0; i < 2; i++ {
			("Subcorrelations i = ", i)
			()
		}
		ch <- "I am a sub-coroutine and I need to finish my work"
	}()
	str := <-ch //Block before there is no data	("str = ", str)
}

Unbuffered channel

ch := make(chan int, 0)

package main
import (
	"fmt"
	"time"
)
func main() {
	//Create a channel without cache	ch := make(chan int, 0)

	//The number of remaining data in the len(ch) buffer, cap(ch) buffer size	("len(ch) = %d, cap(ch)= %d\n", len(ch), cap(ch))
	// Create a new coroutine	go func() {
		for i := 0; i < 10000; i++ {
			("Subcorrelations:i = %d\n", i)
			ch <- i //Write content to chan			(1 * )
		}
	}()
	go func() {
		for  {
			num := <-ch //Read the content in the pipeline, before there is no content, block			("num = ", num)
		}

	}()
	for {
	}
}

Buffered channel pipeline

ch := make(chan int, 3)

package main
import (
	"fmt"
	"time"
)
func main() {
	//Create a cached channel	ch := make(chan int, 3)
	//The number of remaining data in the len(ch) buffer, cap(ch) buffer size	("len(ch) = %d, cap(ch)= %d\n", len(ch), cap(ch))
	// Create a new coroutine	go func() {
		for i := 0; i < 10; i++ {
			ch <- i //Write content to chan			("Subcorrelations[%d]: len(ch) = %d, cap(ch)= %d\n", i, len(ch), cap(ch))
		}
	}()
	//Delay	(2 * )
	for i := 0; i < 10; i++ {
		num := <-ch //Read the content in the pipeline, before there is no content, block		("num = ", num)
	}
}

Close the channel pipeline

close(ch)

package main
import (
	"fmt"
)
func main() {
	//Create a channel without cache	ch := make(chan int, 3)
	//The number of remaining data in the len(ch) buffer, cap(ch) buffer size	("len(ch) = %d, cap(ch)= %d\n", len(ch), cap(ch))
	// Create a new coroutine	go func() {
		for i := 0; i < 10000; i++ {
			("Subcorrelations:i = %d\n", i)
			ch <- i //Write content to chan			//(1 * )
			if i >10 {
				close(ch)
				break
			}
		}
	}()
	go func() {
		for  {
			if num, ok := <-ch; ok == true {
				("num = ", num)
			} else { //Pipe close				break
			}
		}
	}()
	for {

	}
}

One-way channel pipeline, read and write separation

chan<-   means that data enters the pipeline, only write
<-chan means that the data comes out of the pipeline and is read only

Note: Two-way can be turned into one-way, one-way cannot be turned into two-way

package main
//"fmt"
func main() {
	//Create a channel, two-way	ch := make(chan int)
	//Bidirectional channel can be implicitly converted to unidirectional channel	var writeCh chan&lt;- int = ch //Only write, not read	var readCh &lt;-chan int = ch  //Only read, not write	writeCh &lt;- 666 //Write	//&lt;-writeCh //err,  invalid operation: &lt;-writeCh (receive from send-only type chan&lt;- int)
	&lt;-readCh //read	//readCh <- 666 //Written, err, invalid operation: readCh <- 666 (send to receive-only type <-chan int)	//One-way cannot be converted to two-way	//var ch3 chan int = writeCh //cannot use writeCh (type chan&lt;- int) as type chan int in assignment

}

Pipeline Consumer Producer Model

package main
import (
	"fmt"
)
//This channel can only be written, not readfunc producer(out chan&lt;- int) {
	for i := 0; i &lt; 10; i++ {
		out &lt;- i * i  //Write	}
	close(out)  //closure}
//This channel can only be read, not writtenfunc consumer(data &lt;-chan int) {
	for num := range data {
		("num = ", num)
	}
}
func main() {
	//Create a bidirectional channel	ch := make(chan int)
	//Producer, produce numbers, write to channel	//Open a new coroutine	go producer(ch) //channel parameter transmission, reference transmission	//Consumer, read content from channel and print	consumer(ch)
}

The above is the detailed content of golang channel pipeline. For more information about channel pipelines, please follow my other related articles!