Go Goroutines

Introduction

A goroutine is a function that runs concurrently with other functions.

To create a goroutine, we use the keyword go followed by a function invocation:

package main/*from ww w  . j  a v a 2s.c o m*/

     import "fmt" 

     func f(n int) { 
         for i  := 0; i < 10; i++ { 
             fmt.Println(n, ":", i) 
         } 
     } 

     func main() { 
         go f(0) 
         var input string 
         fmt.Scanln(&input) 
     } 

This program consists of two goroutines.

The first goroutine is implicit and is the main function itself.

The second goroutine is created when we call go f(0).

With a goroutine, the code return immediately to the next line and don't wait for the function to complete.

This is why the call to the Scanln function has been included.

Without it, the program would exit before printing all the numbers.




PreviousNext

Related