Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import (
- "fmt"
- "sync"
- strUtil "github.com/agrison/go-commons-lang/stringUtils"
- )
- func processTexts(id int, texts <-chan string, wg *sync.WaitGroup, output chan<- string) {
- defer wg.Done()
- for text := range texts {
- reversed := strUtil.Reverse(text)
- output <- fmt.Sprintf("thread %d: \"%s\"", id, reversed)
- }
- }
- func main() {
- texts := []string{"Hello", "qwerty", "Golang", "platypus", "тест", "level", "generics"}
- threads := 3
- inputChannels := make([]chan string, threads)
- output := make(chan string, len(texts))
- var wg sync.WaitGroup
- for i := 0; i < threads; i++ {
- inputChannels[i] = make(chan string, len(texts))
- wg.Add(1)
- go processTexts(i+1, inputChannels[i], &wg, output)
- }
- for i, text := range texts {
- threadID := i % threads
- inputChannels[threadID] <- text
- }
- for _, ch := range inputChannels {
- close(ch)
- }
- wg.Wait()
- close(output)
- line := 1
- for result := range output {
- fmt.Printf("line %d, %s\n", line, result)
- line++
- }
- fmt.Println("done")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement