"Using PHP with MySQL" was retired on March 1, 2017. You are now viewing the recommended replacement.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Go Language Overview!
You have completed Go Language Overview!
A "goroutine" is a simple way to make several function calls simultaneously. The work gets split up among all your CPU cores, and they all work on it at the same time.
- A goroutine is a simple way to make several function calls simultaneously. The work gets split up among your CPU cores, and they all work on it at the same time.
- A Go program starts with a single goroutine, which runs the
mainfunction
package main
import (
"fmt"
"time"
)
func longTask() {
fmt.Println("Starting long task")
time.Sleep(3 * time.Second)
fmt.Println("Long task finished")
}
func main() {
longTask()
longTask()
longTask()
}
- The first
longTaskcall runs, sleeps for 3 seconds, and then returns. Then the secondlongTaskcall runs, sleeps for 3 seconds, and so on. Because the calls tolongTaskrun one at a time, the program takes just over 9 seconds to complete. - Prepend the
gokeyword to a function call to launch another goroutine, which runs alongside the first.
go longTask()
go longTask()
go longTask()
- Now calls to
longTaskrun in separate goroutines. After each goroutine kicks off, it goes back to themaingoroutine and launches the next goroutine. - The problem is that as soon as the
maingoroutine finishes, the program exits. So the other goroutines don't get a chance to do anything. So just as a quick fix, we'll add a call toSleepto themainfunction:
go longTask()
go longTask()
go longTask()
time.Sleep(4 * time.Second)
More info
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up