doubiao9775 2016-10-02 01:21
浏览 18
已采纳

运行线程一定时间-在被杀死之前

How do I run 10 threads, for 30 seconds each, and then return to the program execution? For example, I want

  1. 10 threads to be spawned and ran for 30 seconds.
  2. Then all threads killed
  3. Then second() to run (i.e. after all threads have finished executing)

So far I have the following however, when I do this, the threads (obviously) keep executing and CPU usage remains at 100% after 30s:

func main(){
    for i := 0; i < 10; i++{
        go thread()
    }
    time.Sleep(30 * time.Second)
    second()
}

func thread() {
    for {
        // Do stuff
    }
}
  • 写回答

2条回答 默认 最新

  • dongwen7371 2016-10-02 06:24
    关注

    You could use Golang context. Here's some of my code when I was learning it.

    package main
    
    import (
        "fmt"
        "log"
        "time"
    
        "golang.org/x/net/context"
    )
    
    func main() {
        someHandler()
    }
    
    func someHandler() {
        //Create a new context with a timeout duration of six seconds. You also get a cancel function you can call early. 
        //You can also have context end at a certain time, instead of a timeout
        ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(6))
    
        for i := 0; i < 5; i++ {
            go doStuff(ctx, i)
        }
    
        select {
        case <- ctx.Done():
            log.Println("Got a cancel request")
            return
        case <-time.After(time.Second * time.Duration(5)):
            //Here I'm actually ending it earlier than the timeout with cancel().
            log.Println("Timed out")
            cancel()
        }
    
    }
    
    func doStuff(ctx context.Context, num int) {
        for {
            select {
            case <-ctx.Done():
                fmt.Println("Done working")
                return
            default:
                fmt.Println("go", num, "working")
            }
            time.Sleep(time.Second)
        }
    }
    

    Outputs:

    $ go run app.go 
    go 0 working
    go 4 working
    go 2 working
    go 3 working
    go 1 working
    go 1 working
    go 0 working
    go 4 working
    go 3 working
    go 2 working
    go 0 working
    go 4 working
    go 2 working
    go 1 working
    go 3 working
    go 4 working
    go 3 working
    go 0 working
    go 2 working
    go 1 working
    go 3 working
    go 4 working
    go 1 working
    go 0 working
    go 2 working
    2016/10/01 23:25:23 Timed out
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 就很莫名其妙,本来正常的Excel,突然变成了这种一格一页
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?