Summary - Goroutines
- Go course
- Intermediate
- Lesson 6/80
- 4 min
Combine goroutines to write a parallel task.
Summary - Goroutines
In this section you learned goroutines:
- Starting with the go keyword
- Short goroutines with anonymous functions
- Argument copying and loop safety
- The main goroutine and the need to wait
- WaitGroup for production waiting
Now you will combine these to write a parallel task: start a goroutine, wait with WaitGroup, print status with fmt.Println.
Practice Print a parallel task
Inside main, add a go func(){...}() expression and print parallel done with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
go func() {
fmt.Println("paralel tamam")
}()
fmt.Println("paralel tamam")
}Expected output
paralel tamam
Practice Produce parallel output
Inside main, print parallel work with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
fmt.Println("paralel iş")
}Expected output
paralel iş
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 WaitGroup usage
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer ____()
fmt.Println("ok")
}()
wg.Wait()
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("ok")
}()
wg.Wait()
Explanation: wg.Done() decrements the counter.
2 Match section concepts
| Term | Meaning |
|---|---|
go |
Start |
goroutine |
Lightweight thread |
WaitGroup |
Wait |
channel |
Communication |