Concurrent Data Access with Mutexes | Challenge

GoGoBeginner
Practice Now

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

Introduction

This challenge aims to demonstrate how to use mutexes to safely access data across multiple goroutines.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/ConcurrencyGroup(["`Concurrency`"]) go/ConcurrencyGroup -.-> go/mutexes("`Mutexes`") subgraph Lab Skills go/mutexes -.-> lab-15410{{"`Concurrent Data Access with Mutexes | Challenge`"}} end

Mutexes

The problem to be solved in this challenge is to increment a named counter in a loop using multiple goroutines, and ensure that the access to the counter is synchronized.

Requirements

  • Use a Container struct to hold a map of counters.
  • Use a Mutex to synchronize access to the counters map.
  • The Container struct should have an inc method that takes a name string and increments the corresponding counter in the counters map.
  • The inc method should lock the mutex before accessing the counters map, and unlock it at the end of the function using a defer statement.
  • Use the sync.WaitGroup struct to wait for the goroutines to finish.
  • Use the fmt.Println function to print the counters map.

Example

## Running the program shows that the counters
## updated as expected.
$ go run mutexes.go
map[a:20000 b:10000]

## Next we'll look at implementing this same state
## management task using only goroutines and channels.

Summary

In this challenge, we learned how to use mutexes to safely access data across multiple goroutines. We created a Container struct to hold a map of counters, and used a Mutex to synchronize access to the counters map. We also implemented an inc method to increment the named counter, and used the sync.WaitGroup struct to wait for the goroutines to finish. Finally, we printed the counters map using the fmt.Println function.

Other Go Tutorials you may like