Advertisement
abstract_abstract

Untitled

Dec 26th, 2024
498
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.02 KB | None | 0 0
  1. import (
  2.     "fmt"
  3.     "sync"
  4.     strUtil "github.com/agrison/go-commons-lang/stringUtils"
  5. )
  6.  
  7. func processTexts(id int, texts <-chan string, wg *sync.WaitGroup, output chan<- string) {
  8.     defer wg.Done()
  9.     for text := range texts {
  10.         reversed := strUtil.Reverse(text)
  11.         output <- fmt.Sprintf("thread %d: \"%s\"", id, reversed)
  12.     }
  13. }
  14.  
  15. func main() {
  16.     texts := []string{"Hello", "qwerty", "Golang", "platypus", "тест", "level", "generics"}
  17.     threads := 3
  18.     inputChannels := make([]chan string, threads)
  19.     output := make(chan string, len(texts))
  20.     var wg sync.WaitGroup
  21.  
  22.     for i := 0; i < threads; i++ {
  23.         inputChannels[i] = make(chan string, len(texts))
  24.         wg.Add(1)
  25.         go processTexts(i+1, inputChannels[i], &wg, output)
  26.     }
  27.  
  28.     for i, text := range texts {
  29.         threadID := i % threads
  30.         inputChannels[threadID] <- text
  31.     }
  32.  
  33.     for _, ch := range inputChannels {
  34.         close(ch)
  35.     }
  36.  
  37.     wg.Wait()
  38.     close(output)
  39.  
  40.     line := 1
  41.     for result := range output {
  42.         fmt.Printf("line %d, %s\n", line, result)
  43.         line++
  44.     }
  45.  
  46.     fmt.Println("done")
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement