doujiao1538 2018-05-19 14:11
浏览 17
已采纳

无限的goroutines,直到收到期望的响应

I'm trying launch goroutines in an infinite loop until I get the response I'm looking for but the select is unreachable if I change for i := 0; i < 10; i++ {} to for {}. What's a pattern for solving this?

package main

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

func myFunc() float64 {

    c := make(chan float64)

    for i := 0; i < 10; i++ {
        go func() {

            var value float64
            value = someOp()

            if value > .9 {
                c <- value
            }

        }()
    }

    // unreachable code the if the for loop above is infinite
    for {
        select {
        case x := <-c:
            return x
        default:
        }
    }

}

func someOp() float64 {
    rand.Seed(time.Now().UnixNano())
    return rand.Float64()
}

func main() {
    fmt.Println(myFunc())
}
  • 写回答

1条回答 默认 最新

  • dougutuo9879 2018-05-19 14:40
    关注

    Starting an unlimited number of goroutines is usually not a good idea. A better approach is to start a fixed number of goroutines that loop looking for an answer. Return from these goroutines when an answer is found.

    func myFunc() float64 {
        c := make(chan float64, 1) // Size 1 prevents race between main goroutine and workers
    
        done := make(chan struct{})
        defer close(done)
    
        // Start a fixed number of goroutines
        for i := 0; i < 10; i++ {
            go func() {
                for {
                    select {
                    case <-done:
                        // myfunc exited with result, return from this goroutine
                        return
                    default:
                        var value float64
                        value = someOp()
                        if value > .9 {
                            select {
                            case c <- value:
                                // This is first goroutine to send a value
                            default:
                                // Another goroutine sent a value
                            }
                            return
                        }
    
                    }
                }
            }()
        }
        return <-c
    }
    

    https://play.golang.org/p/SRpeT8k34eA

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?