Atomic functions

Atomic functions provide low-level locking mechanisms for synchronizing access to integers and pointers.

  1. var (
  2. counter int64
  3. wg sync.WaitGroup
  4. )
  5. func main() {
  6. wg.Add(2)
  7. go incCounter(1)
  8. go incCounter(2)
  9. wg.Wait()
  10. fmt.Println("Final Counter:", counter)
  11. }
  12. func incCounter(id int) {
  13. defer wg.Done()
  14. for count := 0; count < 2; count++ {
  15. atomic.AddInt64(&counter, 1)
  16. runtime.Gosched()
  17. }
  18. }

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.

  1. var (
  2. counter int
  3. wg sync.WaitGroup
  4. mutex sync.Mutex
  5. )
  6. func main() {
  7. wg.Add(2)
  8. go incCounter(1)
  9. go incCounter(2)
  10. wg.Wait()
  11. fmt.Printf("Final Counter: %d\\n", counter)
  12. }
  13. func incCounter(id int) {
  14. defer wg.Done()
  15. for count := 0; count < 2; count++ {
  16. mutex.Lock()
  17. // The use of the curly brackets is just to make the
  18. // critical section easier to see; they’re not necessary.
  19. {
  20. value := counter
  21. runtime.Gosched()
  22. value++
  23. counter = value
  24. }
  25. mutex.Unlock()
  26. }
  27. }