Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

goroutine not finished yet

  • go

In this example we told the first call to run 30 times, but it could only run 6 times before the main part of the code finished that killed the whole process. So we need to be able to wait till the go-routine finishes.

package main

import (
	"fmt"
	"time"
)

func count(n int, name string) {
	for i := 0; i < n; i++ {
		fmt.Printf("%s %d\n", name, i)
		time.Sleep(1000)
	}
}

func main() {
	fmt.Println("Welcome")
	go count(30, "first")
	count(3, "second")
	count(3, "third")
	fmt.Println("Done")
}
Welcome
second 0
second 1
first 0
second 2
first 1
third 0
first 2
first 3
third 1
first 4
third 2
first 5
Done