乐趣区

关于go:golang控制gorountine顺序执行

golang 管制 gorountine 程序执行

package main

import ("fmt")

func main() {sort()
}

func sort() error {
    var count int
    capChan := 100
    exit := make(chan int, capChan)

    for i := 0; i < capChan; i++ {flag := make(chan int)
        go func(i int) {
            exit <- i
            flag <- i
        }(i)
        <-flag
    }

LOOP:
    for {
        select {
        case msg, ok := <-exit:
            count++
            fmt.Println("---", msg, ok)
            break
        default:
            if count >= capChan {break LOOP}
        }
    }
    defer func() {close(exit)
    }()
    return nil
}
退出移动版