Atomic functions
Atomic functions provide low-level locking mechanisms for synchronizing access to integers and pointers.
var (
counter int64
wg sync.WaitGroup
)
func main() {
wg.Add(2)
go incCounter(1)
go incCounter(2)
wg.Wait()
fmt.Println("Final Counter:", counter)
}
func incCounter(id int) {
defer wg.Done()
for count := 0; count < 2; count++ {
atomic.AddInt64(&counter, 1)
runtime.Gosched()
}
}
Mutexes
A mutex is used to create a critical section around code that ensures only one goroutine at a time can execute that code section.
var (
counter int
wg sync.WaitGroup
mutex sync.Mutex
)
func main() {
wg.Add(2)
go incCounter(1)
go incCounter(2)
wg.Wait()
fmt.Printf("Final Counter: %d\\n", counter)
}
func incCounter(id int) {
defer wg.Done()
for count := 0; count < 2; count++ {
mutex.Lock()
// The use of the curly brackets is just to make the
// critical section easier to see; they’re not necessary.
{
value := counter
runtime.Gosched()
value++
counter = value
}
mutex.Unlock()
}
}