golang简单输出HELLO, WORLD!问题出在哪?

package main

import (
    "fmt"
    "runtime"
    "strings"
    "sync"
)

const words = "hello, world!"

var wg sync.WaitGroup
var finalWords string

func main() {
    runtime.GOMAXPROCS(runtime.NumCPU())
    c := make(chan string)
    cc := make(chan string)

    wg.Add(len(words))
    for i := 0; i < len(words); i++ {
        go toUppercase(c, cc)
        go addWords(cc)
        c <- string(words[i])
    }

    wg.Wait()
    fmt.Println(words, finalWords)
}

func toUppercase(word chan string, cc chan string) {
    w, ok := <-word
    if !ok {
        // close(cc)
        return
    }
    var upperWord = strings.ToUpper(w)
    cc <- upperWord
}

func addWords(word chan string) {
    w, ok := <-word
    if !ok {
        // close(word)
        return
    }
    finalWords += w
    wg.Done()

}

共 4 个回复


samete

我的这段代码错在哪?为什么不能正确的输出HELLO, WORLD!啊?

# 0

jtgogogo

  1. 我这边可以输出HELLO, WORLD!
  2. 多个toUppercase goroutine写cc chan的顺序并没有严格控制,有可能出现乱序
  3. 多个addWord goroutine并发操作finalWords 全局变量没有做互斥
# 1

samete

哦,谢谢!我试试看

# 2

samete

package main

import (
    "fmt"
    "runtime"
    "strings"
    "sync"
)

const words = "hello, world!"

var wg sync.WaitGroup
var finalWords string

// var mutex sync.Mutex

func main() {
    runtime.GOMAXPROCS(runtime.NumCPU())
    c := make(chan string)
    cc := make(chan string)

    for i := 0; i < len(words); i++ {
        wg.Add(2)
        go toUppercase(c, cc)
        go addWords(cc)
        c <- string(words[i])
        wg.Wait()
    }

    fmt.Println(words, finalWords)
}

func toUppercase(word chan string, cc chan string) {
    w, ok := <-word
    if !ok {
        close(word)
        return
    }
    var upperWord = strings.ToUpper(w)
    cc <- upperWord
    wg.Done()
}

func addWords(word chan string) {
    w, ok := <-word
    if !ok {
        close(word)
        return
    }
    // mutex.Lock()
    finalWords += w
    // mutex.Unlock()
    wg.Done()

}

我改成这样了,可以正确的输出,但是我没加锁

# 3