Goroutines

First, let's examine the most basic Go concurrency feature: the goroutine. Any normal function, when called, will execute the code inside and exit when return is encountered, or the function exits—at which point it will return control to the function that invoked it. A goroutine is one that starts execution, but immediately returns control to the function calling it—essentially creating a background process for each invocation. Any function can be called as a goroutine simply by prefixing go to the invocation, as follows:

package main

import (
"fmt"
"time"
)

func tick(message string) {
for i := 0; i < 5; i++ {
time.Sleep(10 * time.Millisecond)
fmt.Println(message)
}
}

func main() {
go tick("goroutine")
tick("function")
}

This code sample defines a tick(string) method that will output the requested message every 10 milliseconds. The main() function calls this code in two different ways: first, it is invoked as a goroutine, and then as a normal function call. If this were invoked as two function calls, one after the other, we would see a lot of copies of "goroutine" output to the command line, followed by "function" many times. Instead, however, the goroutine executes concurrently with the following code, and so we see this output instead:

Concurrent output with a goroutine

What you see may be slightly different, as the order appears a little random. What you should see is that each pair of output lines say either "goroutine" or "function" with a small time gap between them. The order of each pair will depend on the scheduler, but what you can clearly see is that two invocations of the tick function were running at the same time (that is, concurrently). Goroutines are not limited to such trivial examples but as they occupy the same address space (like a normal function call), they have access to shared areas of memory. When multiple threads can write to the same area of memory, synchronization is typically required to ensure correct operation. To provide better semantics for communicating in this way, the Go language has a feature named channels

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

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