使用频道来交替打印

时间:2017-09-06 02:42:43

标签: go

我想要打印代码:

12AB34CD56EF78GH910IJ

但它打印出来:

12AB3456CDEF78910GHIJ

我很困惑,我认为这很奇怪。

package main

import (
    "fmt"
    "sync"
)

func main() {
    numdone := make(chan int)
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
            defer wg.Done()
            data := []byte("ABCDEFGHIJ")
            for i := 0; i < 10; i = i + 2 {
                    <-numdone
                    fmt.Printf("%c", data[i])
                    fmt.Printf("%c", data[i+1])
            }
    }()

    wg.Add(1)
    go func() {
            defer wg.Done()
            for i := 1; i < 11; i = i + 2 {
                    fmt.Printf("%d", i)
                    fmt.Printf("%d", i+1)
                    numdone <- i
            }
    }()

    wg.Wait()
}

1 个答案:

答案 0 :(得分:1)

请阅读上面的评论。要进行同步,只需使用互斥锁,它就可以工作:

package main

import (
    "fmt"
    "sync"
)

var mu sync.Mutex

func main() {
    numdone := make(chan int)
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        data := []byte("ABCDEFGHIJ")
        for i := 0; i < 10; i = i + 2 {
            <-numdone
            fmt.Printf("%c", data[i])
            fmt.Printf("%c", data[i+1])
            mu.Unlock()
        }
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        for i := 1; i < 11; i = i + 2 {
            mu.Lock()
            fmt.Printf("%d", i)
            fmt.Printf("%d", i+1)
            numdone <- i
        }
    }()

    wg.Wait()
}

游乐场:https://play.golang.org/p/71Dv0iKTy_