Creating a goroutine

In this subsection, you will learn two ways for creating goroutines. The first one is using regular functions, while the second method is using anonymous functions—these two ways are equivalent.

The name of the program covered in this section is simple.go, and it is presented in three parts.

The first part of simple.go is the following Go code:

package main 
 
import ( 
    "fmt" 
    "time" 
) 
 
func function() { 
    for i := 0; i < 10; i++ { 
        fmt.Print(i) 
    } 
    fmt.Println() 
} 

Apart from the import block, the preceding code defines a function named function() that will be used in a short while.

The second part of simple.go follows next:

func main() { 
    go function() 

The preceding code starts with function() as a goroutine. After this, the program continues its execution, while function() begins to run in the background.

The last code portion of simple.go is shown in the following Go code:

go func() { 
    for i := 10; i < 20; i++ { 
        fmt.Print(i, " ") 
    } 
}() 
 
    time.Sleep(1 * time.Second) 
} 

With this code, you create a goroutine using an anonymous function. This method works best for relatively small functions. However, if you have lots of code, it is considered better practice to create a regular function and execute it using the go keyword.

As you will see in the next section, you can create multiple goroutines any way you wish, including using a for loop.

Executing simple.go two times will generate the following type of output:

$ go run simple.go
10 11 12 13 14 0123456789
15 16 17 18 19
$ go run simple.go
10 11 12 13 14 15 16 17 18 19 0123456789  

Although what you really want from your programs is to generate the same output for the same input, the output you get from simple.go is not always the same. The preceding output supports the fact that you cannot control the order in which your goroutines will be executed without taking extra care. This means writing extra code specifically for this to occur. In Chapter 10, Go Concurrency – Advanced Topics, you will learn how to control the order in which your goroutines are executed as well as how to print the results of one goroutine before printing the results of the following one.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.182.76