Go “未被发现”;“僵局”;当你从频道里读的时候

Go “未被发现”;“僵局”;当你从频道里读的时候,go,deadlock,channel,Go,Deadlock,Channel,当从复杂程序(例如web服务器)中的通道读取不确定数量任务的执行结果时,如何处理未检测到的死锁 package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UTC().UnixNano()) results := make(chan int, 100) // we can't know how many tasks there wil

当从复杂程序(例如web服务器)中的通道读取不确定数量任务的执行结果时,如何处理未检测到的死锁

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UTC().UnixNano())

    results := make(chan int, 100)

    // we can't know how many tasks there will be
    for i := 0; i < rand.Intn(1<<8)+1<<8; i++ {
        go func(i int) {
            time.Sleep(time.Second)
            results <- i
        }(i)
    }

    // can't close channel here 
    // because it is still written in
    //close(results)

    // something else is going on other threads (think web server)
    // therefore a deadlock won't be detected
    go func() {
        for {
            time.Sleep(time.Second)
        }
    }()

    for j := range results {
        fmt.Println(j)
        // we just stuck in here
    }
}
主程序包
进口(
“fmt”
“数学/兰德”
“时间”
)
func main(){
rand.Seed(time.Now().UTC().UnixNano())
结果:=制造(chan int,100)
//我们不知道会有多少任务

对于i:=0;isync.WaitGroup
并等待任务以非阻塞方式完成

var wg sync.WaitGroup

// we can't know how many tasks there will be
for i := 0; i < rand.Intn(1<<8)+1<<8; i++ {
    wg.Add(1)
    go func(i int) {
        time.Sleep(time.Second)
        results <- i
        wg.Done()
    }(i)
}

// wait for all tasks to finish in other thread
go func() {
    wg.Wait()
    close(results)
}()

// execution continues here so you can print results
var wg sync.WaitGroup
//我们不知道会有多少任务

对于i:=0;i抛出:所有goroutine都处于休眠状态-死锁!
;但我明白您的意思