List all items in a buffered channel

Is there a (non-destructive) way to list the entire element in a buffered pipe?

The only thing I can think of is the cycle of all of them, re-enabling them at the end. This is not the smartest approach.

Playground Link

c := make(chan int, 100) c <- 111 c <- 222 for i:=0;i<2;i++ { element := <- c fmt.Println(element) c <- element } fmt.Println(len(c)) 
+5
source share
3 answers

This thread from 2011 suggested some kind of shell around the channel to include the Peek () function, but it was more a workaround than anything else.

 type PeekChanInt struct { in <-chan int out chan int } 

General conclusion:

The synchronous channel has no head (it is like a slice of zero length)

You cannot do this because

  • a) he returns back to the tail of the line, not to the end, and
  • b) the author could get there first, so put can be blocked.

I wanted to use such a feature in the past. This may make sense when there is only one channel consumer (I wanted him to look into the first mouse event to perform a shock test before deciding on its consumption)

You can simulate it using a process acting as an intermediary, but you will have to do this for each type of channel or lose type security.

Remember that there is no buffering, so if you look at a value, you will need to get the value from the other side, which would be equivalent to reading it, but this is wrong because peeking should not have any side effects .

+4
source

No, you cannot, you can write your own blocking queue based on a list if you want to do this.

+4
source

You can not. What you have is the only way, but don't do it if you have parallel access to the chan (and then why are you using chan?).

Elements can be inserted or deleted after checking len and during the for loop.

+1
source

Source: https://habr.com/ru/post/1203425/


All Articles