去哪儿面试题 (Golang实现)多线程顺序输出1-75

FredricZhu · 2019-06-06 19:32:39

给他上个链表 :dog:

package main

import (
    "fmt"
    "time"
)

type null struct{}

func main() {

    n := 75
    current := make(chan null)
    next := make(chan null)
    head := current
    for i := 0; i < n; i++ {
        go print(i, current, next)
        current = next
        next = make(chan null)
    }
    close(head)
    time.Sleep(time.Second)
}

func print(i int, r, s chan null) {
    _, ok := <-r
    if !ok {
        fmt.Println(i + 1)
        if s != nil {
            close(s)
        }
    }
}
#11
更多评论
var a struct {

    Mu sync.RWMutex

    Count int

}


var wg sync.WaitGroup


func main()  {

    wg = sync.WaitGroup{}

    wg.Add(75)

    for i:=1; i<=75; i++ {

        go Add()

    }
    wg.Wait()
}

func Add()  {

    defer wg.Done()

    a.Mu.Lock()

    a.Count++

    fmt.Println(a.Count)

    a.Mu.Unlock()

}
#1

输出结果不稳定,也就是说结果不对

#2