You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

clone.go 1.0 kB

1 year ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package io2
  2. import (
  3. "io"
  4. )
  5. // 复制一个流。注:返回的多个流的读取不能在同一个线程,且如果不再需要读取返回的某个流,那么必须关闭这个流,否则会阻塞其他流的读取。
  6. func Clone(str io.Reader, count int) []io.ReadCloser {
  7. prs := make([]io.ReadCloser, count)
  8. pws := make([]*io.PipeWriter, count)
  9. for i := 0; i < count; i++ {
  10. prs[i], pws[i] = io.Pipe()
  11. }
  12. go func() {
  13. pwCount := count
  14. buf := make([]byte, 4096)
  15. var closeErr error
  16. for {
  17. if pwCount == 0 {
  18. return
  19. }
  20. rd, err := str.Read(buf)
  21. for i := 0; i < count; i++ {
  22. if pws[i] == nil {
  23. continue
  24. }
  25. err := WriteAll(pws[i], buf[:rd])
  26. if err != nil {
  27. pws[i] = nil
  28. pwCount--
  29. }
  30. }
  31. if err == nil {
  32. continue
  33. }
  34. closeErr = err
  35. break
  36. }
  37. for i := 0; i < count; i++ {
  38. if pws[i] == nil {
  39. continue
  40. }
  41. pws[i].CloseWithError(closeErr)
  42. }
  43. }()
  44. return prs
  45. }
  46. /*
  47. func BufferedClone(str io.Reader, count int, bufSize int) []io.ReadCloser {
  48. }
  49. */