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, thenc.Value()→0c.Inc()three times, thenc.Value()→3var e Counter, 100 goroutines calle.Inc()100 times each, thene.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.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.