Are golang channels based on LIFO? [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Are golang channels based on LIFO? [duplicate]



This question already has an answer here:



I was wondering regarding the order of elements in golang channels. After running a few examples, it seems that the order in which the elements come off the channel is "last in first out". Am I right?



The following snippet is the example which I used. After running the code, the output is 20 10, while 10 was sent to the channel first and 20 last.


package main

import "fmt"

func multiply(c chan int, num int)
c <- num * 10


func main()
c := make(chan int)

go multiply(c, 1)
go multiply(c, 2)

v1 := <-c
v2 := <-c
fmt.Println(v1, v2)



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





Note that the two goroutines could execute in either order: there's no particular reason to expect that 10 will be sent first.
– David Maze
Aug 12 at 13:02




1 Answer
1



Golang channels are not LIFO.



Channels act as first-in-first-out queues. For example, if one
goroutine sends values on a channel and a second goroutine receives
them, the values are received in the order sent.



Values sent on the channel will be received whenever the receiver of the channel is ready. And if not then it will block. For managing that you can go for buffered channels.



Below code will check if the values are available to be received from the channel.


package main

import "fmt"

func multiply(c chan int, num int)
c <- num * 10


func main()
c := make(chan int, 3)

go multiply(c, 1)
go multiply(c, 2)
go multiply(c, 3)

for i:=0;i<3;i++
foo, ok := <- c
if !ok
fmt.Println("done")
return

fmt.Println(foo)





Working code on Go playground



Buffered Channels



Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channel:


make(chan int, 100)



The capacity, in number of elements, sets the size of the buffer in
the channel. If the capacity is zero or absent, the channel is
unbuffered and communication succeeds only when both a sender and
receiver are ready. Otherwise, the channel is buffered and
communication succeeds without blocking if the buffer is not full
(sends) or not empty (receives). A nil channel is never ready for
communication.



In your case, it depends on which go routine will send the value on the channel first. The values that you are printing completely depends on the go routines.



For more information go through Golang Channels

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard