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

grpc stream use async socket send, but seem use them same buffer, the newer msg seems overwrite the underlying buffer #2671

Open
dashessmith opened this issue Nov 9, 2023 · 4 comments

Comments

@dashessmith
Copy link

image

@dashessmith
Copy link
Author

image

this bytes.buffer seems not thread safe

@DingYuan0118
Copy link

Encounter the same problem. Use grpc server seems to avoid this

@DingYuan0118
Copy link

image Seems all buf in channel use the same pointer which point to the underlying []byte since buf.Reset() does not change buf's address buf.Bytes() always return the same pointer.

use copy() to make a new []byte and then put it into channel can solve this.

func TestBuffer(t *testing.T) {
	wg := sync.WaitGroup{}
	defer wg.Wait()

	var ch = make(chan []byte, 128)
	wg.Add(1)
	go func() {
		defer wg.Done()

		buf := bytes.Buffer{}

		defer close(ch)

		for i := 1; i < 10; i++ {
			buf.Write([]byte(fmt.Sprintf("%v", i)))
			bs := buf.Bytes()
			buf.Reset()
			b := make([]byte, len(bs))
			copy(b, bs)
			ch <- b
		}

	}()

	wg.Add(1)

	go func() {
		defer wg.Done()
		for x := range ch {
			fmt.Printf("i:=%v\n", string(x))
		}
	}()
}


i:=1
i:=2
i:=3
i:=4
i:=5
i:=6
i:=7
i:=8
i:=9

@DingYuan0118
Copy link

image

Change like this seems to make it work normal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants