dory4404 2018-06-20 23:54 采纳率: 0%
浏览 143
已采纳

更改goroutine睡眠时间

In Go I can write such code for creating a gorouting that sleeps 5 sec.

func sleep(link chan interface{}){
    time.Sleep(5 * time.Second)
    fmt.Println("I've slept for 5 sec")
    link <- struct {}{}
}

func main() {
    var link = make(chan interface{})
    go sleep(link)
    time.Sleep(1 * time.Second)
    // here I want to change the remaining sleeping time of `sleep` goroutine to 0.5 sec
    <- link
}

What if in main function I change my mind and decide that the sleeper should sleep not 5 sec but 3. How can it done if goroutine already started to sleep (and sleeping, for example, for 1 sec)?

UPDATE

I mean is there something whereby I can manage that unique goroutine while it sleeps. Like giving commands to it about decreasing or increasing time of sleep:

func main() {
    // ...
    time.Sleep(1)
    something.ManageRemainingTime(10)
    time.Sleep(5)
    something.ManageRemainingTime(100)
    time.Sleep(8)
    something.ManageRemainingTime(0.5)
    // ...
}
  • 写回答

3条回答 默认 最新

  • dongtangu8403 2018-06-21 00:28
    关注

    If you just need a way to "wakeup" a sleeping goroutine, you could use sync.Once to ensure your function only gets called once, and then return a channel so you can set a sooner "trigger time", so something this:

    func sleep(callback func(), seconds int) chan int {
        once := sync.Once{}
        wakeup := make(chan int)
        go func() {
            for sleep := range wakeup {
                go func() {
                    time.Sleep(time.Duration(sleep) * time.Second)
                    once.Do(callback)
                }()
            }
        }()
        wakeup <- seconds
        return wakeup
    }
    
    
    func main() {
            wg := sync.WaitGroup{}
            wg.Add(1)
            t := time.Now()
            wakeup := sleep(func() {
                fmt.Println("Hello, playground")
                wg.Done()
            }, 5)
            wakeup <- 2
            wg.Wait()
            fmt.Println(time.Since(t))
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable