Golang多线程垂直输出字符串

[本文出自天外归云的博客园]

三个字符串,abc,def,ghi,请用多线程顺序输出:adg,beh,cfi

抛砖引玉,我的代码如下:

package main

import "fmt"
import "sync"

func printStr(a, b, c string) {
        strLen := len(a)
        var wg sync.WaitGroup
        wg.Add(strLen)
        msgs := make(chan string, strLen)
        go func() {
                for i := 0; i < strLen; i++ {
                        defer wg.Done()
                        fmt.Print(<- msgs)
                }
        } ()
        for i := 0; i < strLen; i++ {
                msgs <- fmt.Sprintf("%+v%+v%+v\n", string(a[i]), string(b[i]), string(c[i]))
        }
        wg.Wait()
}

func main() {
        a := "abc"
        b := "def"
        c := "ghi"
        printStr(a, b, c)
}

你还有更好的办法吗?

posted @ 2022-06-30 12:22  天外归云  阅读(41)  评论(0编辑  收藏  举报