Guest User

Untitled

a guest
Nov 19th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. // Slice sharing problem.
  2.  
  3. package main
  4.  
  5. import (
  6. "bytes"
  7. "context"
  8. "fmt"
  9. "io"
  10. "strings"
  11. "time"
  12. )
  13.  
  14. func consumer(ctx context.Context, in <-chan []byte) {
  15. for {
  16. select {
  17. case <-ctx.Done():
  18. return
  19. case data := <-in:
  20. fmt.Printf("%#v\n", string(data))
  21. }
  22. }
  23. }
  24.  
  25. func produce(reader io.Reader, out chan<- []byte) {
  26. var buf [4]byte
  27. for {
  28. n, err := reader.Read(buf[:])
  29. if err != nil {
  30. break
  31. }
  32. if n > 0 {
  33. if strings.Trim(string(buf[:n]), " \r\n\t") == "quit" {
  34. break
  35. }
  36. out <- buf[:n]
  37. }
  38. }
  39. }
  40.  
  41. func main() {
  42. ctx, cancel := context.WithCancel(context.Background())
  43. defer cancel()
  44. const data = "1234567890abcdef"
  45. ch := make(chan []byte)
  46. go consumer(ctx, ch)
  47. produce(bytes.NewReader([]byte(data)), ch)
  48. time.Sleep(16 * time.Millisecond)
  49. }
Add Comment
Please, Sign In to add comment