Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Slice sharing problem.
- package main
- import (
- "bytes"
- "context"
- "fmt"
- "io"
- "strings"
- "time"
- )
- func consumer(ctx context.Context, in <-chan []byte) {
- for {
- select {
- case <-ctx.Done():
- return
- case data := <-in:
- fmt.Printf("%#v\n", string(data))
- }
- }
- }
- func produce(reader io.Reader, out chan<- []byte) {
- var buf [4]byte
- for {
- n, err := reader.Read(buf[:])
- if err != nil {
- break
- }
- if n > 0 {
- if strings.Trim(string(buf[:n]), " \r\n\t") == "quit" {
- break
- }
- out <- buf[:n]
- }
- }
- }
- func main() {
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- const data = "1234567890abcdef"
- ch := make(chan []byte)
- go consumer(ctx, ch)
- produce(bytes.NewReader([]byte(data)), ch)
- time.Sleep(16 * time.Millisecond)
- }
Add Comment
Please, Sign In to add comment