Golang canals keep order

Do Go channels have any order guarantees?

For example: you have two goroutines A and B that use the channel. A clicks data on the channel, and B reads it. Are you sure B will read the data. In the same order that A placed it in the channel?

I understand that if there are several producers or consumers, the order can be non-deterministic, but I specifically ask about the presence of only one manufacturer and 1 consumer.

EDIT: I ask about buffered channels

thanks

+4
source share
2 answers

You can see the channel idea illustrated in " The nature of channels in transit" : it shows how order or reading / writing was respected.
See Also Channels :

Receivers are always blocked until data is received.

  • If the channel is unbuffered, the sender blocks until the receiver receives a value.
  • If the channel has a buffer, the sender is blocked only until the value is copied to the buffer; if the buffer is full, it means until a receiver receives a value.

Unbuffered channels

http://3.bp.blogspot.com/-vnJIWvlbP-E/UwDVICJKB9I/AAAAAAAANX0/T04V_58i8Vs/s1600/Screen+Shot+2014-02-16+at+10.10.54+AM.png

Buffered channel

http://1.bp.blogspot.com/-GkVAtGeUzrs/UwIQ6AezJmI/AAAAAAAANYE/5XWpxN-zA3w/s1600/Screen+Shot+2014-02-17+at+8.38.15+AM.png

+22
source

I read The Nature of Channels In Go 's blog, but I still confuse why the code below outputs -5 17 (I expect it outputs 17 -5)

package main import "fmt" func sum(s []int, c chan int) { sum := 0 for _, v := range s { sum += v } c <- sum // send sum to c } func main() { s := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(s[:len(s)/2], c) go sum(s[len(s)/2:], c) x := <-c y := <-c fmt.Println(x, y) } 

and the codes below: 17 -5 (as expected)

 package main import "fmt" func sum(s []int, c chan int) { sum := 0 for _, v := range s { sum += v } c <- sum // send sum to c } func main() { s := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(s[:len(s)/2], c) x := <-c // Only difference here go sum(s[len(s)/2:], c) y := <-c fmt.Println(x, y) } 

This code is from Walk along the way

+1
source

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


All Articles