为了账号安全,请及时绑定邮箱和手机立即绑定

go中的非阻塞通道

go中的非阻塞通道

Go
牛魔王的故事 2023-04-17 15:10:14
我有一些这样的代码:go func(ch chan bool) chan bool {    // some processing    ch <- true    return ch}(ch)for i := 0; i < TotalQuestions; i++ {    // check if channel ch has some value    // If it has then execute below statements, else break out of the loop    fmt.Println(questions[i])    answer, _ := InputReader.ReadString('\n')    // some processing}fmt.Println("Your Total score is " + strconv.Itoa(TotalScore) + " out of " + strconv.Itoa(TotalQuestions))现在我要做的是检查通道 ch 是否有值(在 for 循环中)。如果它有一个值,那么我想跳出 for 循环来打印最后一条语句。否则,我想继续我的循环。我试图插入选择块,但没有用(通道被阻塞,代码没有打印问题)。怎么做?
查看完整描述

2 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

package main

    

import (

    "fmt"

    "log"

    "math/rand"

    "time"

)


func main() {


    // user score, no.of questions asked so far

    var score, num int

    var correct bool // temporary variable to decide if the answer is right

    // questions

    var questions = make([]string, 13)


    t1 := time.Tick(time.Second * 7) // timer loop:

    for {

        select {

        case <-t1:

            log.Println("ran out of time")

            break loop

        default:

            // have any questions further questions to ask

            if num < len(questions) {


                // simulate typing

                time.Sleep(time.Millisecond * 777)


                // correct or wrong answer

                correct = (rand.Intn(777)%2 == 0)


                if correct {

                    fmt.Println("you did it")

                    score++ //increase score

                } else {

                    fmt.Println("try again")

                }


            } else {

                // no questions, state and break

                log.Println("all questions were finished")

                break loop //break loop, all questions were finished

            }

            num++

        }

    }


    //print final score

    fmt.Println("your score is:", score)

}


查看完整回答
反对 回复 2023-04-17
?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

以非阻塞方式从通道读取的功能方式:


func CollectChanOne[T any](ch <-chan T) (T, bool) {

    select {

    case val, stillOpen := <-ch:

        return val, stillOpen

    default:

        var zeroT T

        return zeroT, false

    }

}

示例: https: //go.dev/play/p/Njwyt32B4oT


注意此示例还有另一种方法 CollectChanRemaining() ,它读取通道中的所有缓冲元素。


查看完整回答
反对 回复 2023-04-17
  • 2 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信