douyao3895 2018-01-20 16:00
浏览 31
已采纳

如何安排运行的非阻塞功能

My questions is how to schedule running independent non-blocking functions every interval N.

My initial approach is to use go channels within a select statement to receive the values in a non-blocking manner and use time.Sleep(N) in each function to schedule the call.

In the code snippet below, this only for the first run; however, after the first call, it keeps calling computeY() repeatedly without respecting the time.Sleep() call.

    package main

    import (
        "fmt"
        "time"
    )

    var (
        x string = ""
        y string = ""
    )

    func computeY(c chan string) {
        time.Sleep(10 * time.Second)
        fmt.Println("I'm in Y")

        y = "this is Y value"
        c <- y
    }

    func computeX(c chan string) {
        time.Sleep(1 * time.Second)

        x = "this is X value"
        c <- x
    }

    func main() {
        xC := make(chan string)
        yC := make(chan string)

        for {
            go computeX(xC)
            go computeY(yC)

            select {
            case x := <-xC:
                fmt.Println(fmt.Sprintf("X: %v, Y: %v", x, y))
            case y := <-yC:
                fmt.Println(fmt.Sprintf("X: %v, Y: %v", x, y))
            }

        }
    }
  • 写回答

2条回答 默认 最新

  • doudun6928 2018-01-20 16:06
    关注

    You are calling both computeX and computeY every iteration of the loop.

    Since computeX takes 1s, the for loop iterates once per second and an extra time when yC gets a value.

    This means that you're running go computeY at t=0s, t=1s, t=2s, etc.... The first one terminates at t=10s, the second at t=11s, etc...

    If you want to make sure you only schedule one computeX and computeY at a time, you need to change your main to something along the lines of:

        go computeX(xC)
        go computeY(yC)
        for {
            select {
            case x = <-xC:
                fmt.Printf("Finished computeX: X: %v, Y: %v
    ", x, y)
                go computeX(xC)
            case y = <-yC:
                fmt.Printf("Finished computeY: X: %v, Y: %v
    ", x, y)
                go computeY(yC)
            }
        } 
    

    A few other things to note about your code:

    • x and y are global and assigned in computeX and computeY
    • your channel reads shadow x and y
    • fmt.Println(fmt.Sprintf("...")) is just fmt.Printf("... ")
    • you don't need to initialize strings to "", that's the default value
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计