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!
Preview
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
we need to run it three times.
0:00
If you made just one
function call at a time,
0:01
it would take around nine seconds,
but that's wasting computing power.
0:03
Your CPU probably has
multiple cores on it.
0:07
A simplified way to think of this
is like having several computers
0:10
inside your computer.
0:13
And if you're making just
one function call at a time,
0:15
only one of those
computers is getting used.
0:18
A go routine is a simple way to make
several function calls simultaneously.
0:21
The work gets split up
among those CPU cores.
0:25
And they all work on it at the same time.
0:28
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