Atomic Counters in Concurrent Go Programming

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This challenge focuses on managing state in Go using the sync/atomic package for atomic counters accessed by multiple goroutines.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/ConcurrencyGroup(["`Concurrency`"]) go/ConcurrencyGroup -.-> go/atomic("`Atomic`") subgraph Lab Skills go/atomic -.-> lab-15374{{"`Atomic Counters in Concurrent Go Programming`"}} end

Atomic Counters

The problem is to increment a counter exactly 1000 times using 50 goroutines and the sync/atomic package.

Requirements

  • Use the sync/atomic package to increment the counter.
  • Use a WaitGroup to wait for all goroutines to finish their work.

Example

## We expect to get exactly 50,000 operations. Had we
## used the non-atomic `ops++` to increment the counter,
## we'd likely get a different number, changing between
## runs, because the goroutines would interfere with
## each other. Moreover, we'd get data race failures
## when running with the `-race` flag.
$ go run atomic-counters.go
ops: 50000

## Next we'll look at mutexes, another tool for managing
## state.

Summary

In this challenge, we learned how to use the sync/atomic package to manage state in Go by incrementing a counter using multiple goroutines. The AddUint64 function was used to atomically increment the counter, and a WaitGroup was used to wait for all goroutines to finish their work.

Other Go Tutorials you may like