zoukankan      html  css  js  c++  java
  • go的超时控制

    然而如果某个 goroutine 运行时间太长了,那很肯定会拖累主 goroutine 被阻塞住,整个程序就挂起在那儿了。因此我们需要有超时的控制。

    通常我们可以通过 select + time.After 来进行超时检查,例如这样,我们增加一个函数 Run() ,在 Run() 中执行 go run() 。并通过 select + time.After 进行超时判断。

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func Run(task_id, sleeptime, timeout int, ch chan string) {
        ch_run := make(chan string)
        go run(task_id, sleeptime, ch_run)
        select {
        case re := <-ch_run:
            ch <- re
        case <-time.After(time.Duration(timeout) * time.Second):
            re := fmt.Sprintf("task id %d , timeout", task_id)
            ch <- re
        }
    }
    
    func run(task_id, sleeptime int, ch chan string) {
    
        time.Sleep(time.Duration(sleeptime) * time.Second)
        ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime)
        return
    }
    
    func main() {
        input := []int{3, 2, 1}
        timeout := 2
        chs := make([]chan string, len(input))
        startTime := time.Now()
        fmt.Println("Multirun start")
        for i, sleeptime := range input {
            chs[i] = make(chan string)
            go Run(i, sleeptime, timeout, chs[i])
        }
    
        for _, ch := range chs {
            fmt.Println(<-ch)
        }
        endTime := time.Now()
        fmt.Printf("Multissh finished. Process time %s. Number of task is %d", endTime.Sub(startTime), len(input))
    }
  • 相关阅读:
    疑问
    linux 7.0+救援模式
    Unity3D手游开发日记(6)
    Unity3D手游开发日记(4)
    Unity3D手游开发日记(5)
    Unity3D手游开发日记(2)
    Unity3D手游开发日记(3)
    Unity3D手游开发日记(1)
    十大最佳Leap Motion体感控制器应用
    unity3d模型不接受光照
  • 原文地址:https://www.cnblogs.com/matengfei123/p/14745906.html
Copyright © 2011-2022 走看看