Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Buffer size in channels : N+2 instead of N in make(chan int, N) #22840

Closed
enimiste opened this issue Nov 21, 2017 · 1 comment
Closed

Buffer size in channels : N+2 instead of N in make(chan int, N) #22840

enimiste opened this issue Nov 21, 2017 · 1 comment

Comments

@enimiste
Copy link

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

go1.9 windows/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

Windows 10 64bits

What did you do?

https://play.golang.org/p/9lzcI2y9Za

package main

import (
	"fmt"
	"strings"
	"sync"
)

func main() {
	log := []string{}
	wg := sync.WaitGroup{}
	wg.Add(2)
	ch := make(chan int, 5)
	go func() {
		for i := 0; i < 15; i++ {
			log = append(log, fmt.Sprintf("Out %d", i))
			ch <- i
		}
		wg.Done()
	}()

	go func() {
		for i := 0; i < 15; i++ {
			x := <-ch
			log = append(log, fmt.Sprintf("In %d", x))
		}

		wg.Done()
	}()
	wg.Wait()
	fmt.Println(strings.Join(log, "\n"))
}

If possible, provide a recipe for reproducing the error.
A complete runnable program is good.
A link on play.golang.org is best

What did you expect to see?

Out 0
Out 1
Out 2
Out 3
Out 4
In 0
In 1
In 2
In 3
In 4
Out 5
Out 6
Out 7
Out 8
Out 9
In 5
In 6
In 7
In 8
In 9
Out 10
Out 11
Out 12
Out 13
Out 14
In 10
In 11
In 12
In 13
In 14

What did you see instead?

Out 0
Out 1
Out 2
Out 3
Out 4
Out 5
Out 6
In 0
In 1
In 2
In 3
In 4
In 5
In 6
Out 7
Out 8
Out 9
Out 10
Out 11
Out 12
Out 13
In 7
In 8
In 9
In 10
In 11
In 12
In 13
Out 14
In 14

Try setting the buffer size to 0 and you will observe that the buffer has the size 2. I think that the real buffer size of this definition : ch := make(chan int, N) is N+2
It is normal ? or an issue ?

@enimiste enimiste changed the title Buffered channels Buffer size in channels : N+2 instead of N in make(chan int, N) Nov 21, 2017
@bradfitz
Copy link
Contributor

This is working as expected.

For questions about Go, see https://golang.org/wiki/Questions. We don't currently use this issue tracker for general Go Q&A.

@golang golang locked and limited conversation to collaborators Nov 21, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants