简体   繁体   English

从函数返回后使goroutine保持运行

[英]Make goroutines stay running after returning from function

in Java I can make threads run for long periods of time and I don't need to stay within the function that started the thread. 在Java中,我可以使线程长时间运行,而不必停留在启动线程的函数中。

Goroutines, Go's answer to Threads seem to stop running after I return from the function that started the routine. Goroutines,Go对线程的回答似乎在我从启动例程的函数返回后停止运行。

How can I make these routines stay running and return from the calling function? 如何使这些例程保持运行并从调用函数返回?

Thanks 谢谢

Goroutines do continue running after the function that invokes them exits: Playground Goroutine 确实会在调用它们的函数退出后继续运行: 游乐场

package main

import (
    "fmt"
    "time"
)

func countToTen() chan bool {
    done := make(chan bool)
    go func() {
        for i := 0; i < 10; i++ {
            time.Sleep(1 * time.Second)
            fmt.Println(i)
        }
        done <- true
    }()
    return done
}

func main() {
    done := countToTen()
    fmt.Println("countToTen() exited")

    // reading from the 'done' channel will block the main thread
    // until there is something to read, which won't happen until
    // countToTen()'s goroutine is finished
    <-done
}

Note that we need to block the main thread until countToTen() 's goroutine completes. 请注意,我们需要阻塞主线程,直到countToTen()的goroutine完成。 If we don't do this, the main thread will exit and all other goroutines will be stopped even if they haven't completed their task yet. 如果我们不这样做,则主线程将退出,并且所有其他goroutine将被停止,即使它们尚未完成任务。

You can. 您可以。

If you want to have a go-routine running in background forever, you need to have some kind of infinite loop, with some kind of graceful stopping mechanism in place, usually via channel. 如果要让go-routine永远在后台运行,则需要具有某种无限循环,并具有某种优美的停止机制(通常是通过通道)。 And invoke the go-routine via some other function, so even after this other function terminates, your go-routine will still be running. 并通过其他函数调用go-routine ,因此即使该其他函数终止,您的go-routine仍将运行。

For example: 例如:

// Go routine which will run indefinitely.
// Unless you send a signal on quit channel.
func goroutine(quit chan bool) {
   for {
      select {
         case <-quit:
           fmt.Println("quit")
           return
         default:
           fmt.Println("Do your thing")
      }
   }
}

// Go routine will still be running, 
// after you return from this function.
func invoker() {
     q := make(chan bool)
     go goroutine(q)
}

Here, you can call invoker , when you want to start the go-routine . 在这里,当您想启动go-routine时,可以调用invoker And even after invoker returns, your go-routine will still be running in background. 即使invoker返回后,您的例程仍将在后台运行。

Only exception to this is, when main function returns all go-routines in the application will be terminated. 唯一的例外是,当main函数返回应用go-routines中的所有go-routines ,它们都会终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM