On Sunday, April 21, 2024 at 11:18:24 AM UTC+12 Taňryberdi Şyhmyradow wrote:
Hello guys,
For the following lines, I wanted to print numbers in ordered, but
couldn't. Could you please help me and explain the reason
Thanks in advance
```
numbers := []int{1, 2, 3, 4, 5}
// Create a buffered channel to handle multiple values
printed := make(chan int, len(numbers))
for _, n := range numbers {
fmt.Println("Sending", n, "to the channel")
go func() {
printed <- n
}() // Pass the value of n by copying it
}
// Receive all values from the channel in a loop
for i := 0; i < len(numbers); i++ {
fmt.Println(<-printed)
}
```
When you start a bunch of goroutines in a loop, there is no guarantee as to
what order the scheduler will start each one.
Thus you will see them delivered in different orders on each run. You have
to decide on some form of synchronization. Maybe you choose to run a single
goroutine worker that will loop over the source slice, and push the values
into the channel in order. Or maybe you will keep using many goroutines but
collect them all in the receiver, sort them after the last value is
received, and then print them out. Or, maybe your receiver will have some
kind of buffering where it collects values and only prints them when it has
the next one in sequence.
--
Tanryberdi Shyhmyradov
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/ae085bdf-544f-4958-b85f-e36dcaea8ca7n%40googlegroups.com.