Skip to content
Exercise · Goroutines and channels · lesson 12 of 13

Exercise: a safe counter

Write a type Counter — a counter that several goroutines can use at the same time. The method func (c *Counter) Inc() raises the counter by one, and func (c *Counter) Value() int returns its current value. Choose the fields of the Counter struct yourself.

  • var c Counter, then c.Value() → 0
  • c.Inc() three times, then c.Value() → 3
  • var e Counter, 100 goroutines call e.Inc() 100 times each, then e.Value() → 10000

Constraints: the zero value of Counter is ready to use and equals 0; Inc and Value are called from different goroutines at the same time; each counter has its own value.

The check runs the tests with the race detector: if several goroutines change a field without synchronisation, the solution fails.

Do not add extra imports unless the task says so explicitly.

counter.go — go
go · 9 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way