concurrency.go 729 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package util
  2. import (
  3. "strings"
  4. )
  5. func mapParallel[in, out any](items []in, fn func(in) out) chan out {
  6. mapChans := make([]chan out, 0, len(items))
  7. for _, v := range items {
  8. ch := make(chan out)
  9. mapChans = append(mapChans, ch)
  10. go func() {
  11. defer close(ch)
  12. ch <- fn(v)
  13. }()
  14. }
  15. resultChan := make(chan out)
  16. go func() {
  17. defer close(resultChan)
  18. for _, ch := range mapChans {
  19. v := <-ch
  20. resultChan <- v
  21. }
  22. }()
  23. return resultChan
  24. }
  25. // WriteStringsPar allows to iterate over a list and compute strings in parallel,
  26. // yet write them in order.
  27. func WriteStringsPar[a any](sb *strings.Builder, items []a, fn func(a) string) {
  28. ch := mapParallel(items, fn)
  29. for v := range ch {
  30. sb.WriteString(v)
  31. }
  32. }