Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Goroutines, Go's answer to Threads seem to stop running after I return from the function that started the routine.

How can I make these routines stay running and return from the calling function?

Thanks

like image 291
jim Avatar asked May 10 '16 15:05

jim


2 Answers

Goroutines do continue running after the function that invokes them exits: Playground

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. 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.

like image 143
weberc2 Avatar answered Nov 15 '22 06:11

weberc2


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. And invoke the go-routine via some other function, so even after this other function terminates, your go-routine will still be running.

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. And even after invoker returns, your go-routine will still be running in background.

Only exception to this is, when main function returns all go-routines in the application will be terminated.

like image 30
Parth Desai Avatar answered Nov 15 '22 06:11

Parth Desai