Go reads the existing cached chan data

There is a concurrent Go coroutine to write data to chan, and the Go main coroutine is responsible for reading (receiving) data.

The Go main coroutine creates a chan queue ch with a capacity of 100, and line 25 passes the ch to the write coroutine. Next, the Go main coroutine sleeps for 2 seconds.
During this period, the write coroutine runs concurrently. The write coroutine has a for loop, which writes 0 to 47 to the chan queue ch in turn, and then sleeps for 0.3 seconds. The buffer chan has a capacity of 100. If it is full, the block will occur until the value in ch is read.

The read operation first determines the number of elements cached in the cache chan queue ch before each read.
If there is no buffer element, sleep for 0.2 seconds.
If there are buffer elements, it is judged whether the number of buffer elements len (ch) is greater than MAXREQLEN (30). If len (ch)> 30, then read 30 elements in one batch, otherwise read len (ch) elements in one batch.
After reading the element, do some thing, and then continue reading.

package main

import (
	"fmt"
	"time"
)

var MAXREQLEN = 30

func write(ch chan int) {
	for {
		for i := 0; i < 47; i++ {
			ch <- i
			fmt.Println("successfully wrote", i, "to ch")
		}
		time.Sleep(300 * time.Millisecond)
	}

	//close(ch)
}
func main() {
	//test()

	ch := make(chan int, 100)
	go write(ch)
	time.Sleep(2 * time.Second)

	for {
		numArr := make([]int, 0)
		bufferChan := len(ch)
		if bufferChan > 0 {
			var max int
			if bufferChan > MAXREQLEN {
				max = MAXREQLEN
			} else {
				max = bufferChan
			}
			for i := 0; i < max; i++ {
				v := <-ch
				fmt.Println("read value", v, "from ch")
				numArr = append(numArr, v)
			}
			fmt.Println(numArr)
			fmt.Println("do some thing")
		}
		time.Sleep(200 * time.Millisecond)
		fmt.Println("Sleep(100 * time.Millisecond)")
	}

}

func test() {
	c := make(chan int, 100)

	fmt.Println("1.len:", len(c))

	for i := 0; i < 34; i++ {
		c <- 0
	}

	fmt.Println("2.len:", len(c))

	<-c

	<-c

	fmt.Println("3.len:", len(c))
}

 

Published 127 original articles · Likes 24 · Visits 130,000+

Guess you like

Origin blog.csdn.net/Linzhongyilisha/article/details/104497519