What is Sync pacage in Golang ?
The sync package in Golang provides synchronization primitives that can be used to coordinate access to shared resources in concurrent programs. Here's an example of using the sync.Mutex type to prevent race conditions when accessing a shared variable:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
var mu sync.Mutex
var sharedVariable int
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
// Acquire the lock to access the shared variable.
mu.Lock()
// Increment the shared variable.
sharedVariable++
// Release the lock.
mu.Unlock()
wg.Done()
}()
}
wg.Wait()
// The value of sharedVariable should be 10, not less or more.
fmt.Println(sharedVariable)
}
In this example, we create a sync.Mutex value named mu to protect access to the shared variable sharedVariable. Each goroutine acquires the lock using the Lock method before incrementing the shared variable, and releases the lock using the Unlock method after incrementing it. This ensures that only one goroutine at a time can access the shared variable, and prevents race conditions. The sync.WaitGroup type is used to wait for all goroutines to finish before printing the final value of the shared variable.
Comments
Post a Comment