Summary - sync package
- Go course
- Intermediate
- Lesson 24/80
- 4 min
Combine Mutex and WaitGroup to write a parallel counter.
Summary - sync package
In this section you learned the sync package:
- Exclusive access with Mutex
- Many readers one writer with RWMutex
- Wait for goroutines with WaitGroup
- Run once with Once and recycle with Pool
Now you combine these into a parallel counter: protect with Mutex, wait with WaitGroup.
Practice Parallel counter
Inside main, add a sync.Mutex declaration and print counter done with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"sync"
)
func main() {
var mu sync.Mutex
mu.Lock()
fmt.Println("sayaç tamam")
mu.Unlock()
}Expected output
sayaç tamam
Practice Sync output
Inside main, print sync ready with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
fmt.Println("sync ready")
}Expected output
sync ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Mutex and WaitGroup
var mu sync.Mutex
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
mu.____()
n++
mu.Unlock()
}()
wg.Wait()
var mu sync.Mutex
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
n++
mu.Unlock()
}()
wg.Wait()
Explanation: Done is deferred, Lock is for protection.
2 Match section concepts
| Term | Meaning |
|---|---|
Mutex |
Exclusive access |
RWMutex |
Read-write |
WaitGroup |
Waiting |
Once |
Once |