Skip to content
Exercise · Multithreading: An Overview · lesson 10 of 10

Exercise: countdown timer

Write the class Countdown, a countdown timer; add the fields yourself. The constructor Countdown(std::chrono::minutes limit) sets the time limit, and the method void spend(std::chrono::milliseconds time) subtracts the time spent from what is left. std::chrono::seconds remaining() const returns the time left in whole seconds, and bool expired() const tells whether the time is up.

  • for Countdown c(1min): c.remaining() → 60s
  • after c.spend(20s) and c.spend(500ms): c.remaining() → 39s
  • after one more c.spend(39s): c.remaining() → 0s, and c.expired() → false

Constraints: limit is greater than zero, and time is not negative. remaining() drops the fraction of a second and returns 0s if the limit is overspent. expired() returns true when not a single millisecond of the limit is left.

durations.cpp — cpp
cpp · 19 lines
Ctrl+Enter run · Esc leave editor