I'm learning C++ since yesterday and I'd like to code an alarm system that lets the user set his own alarms, with an Alarm
object.
What I attempted works right in itself, but only lets the user run one: If I try to use the start
method to start a second alarm, the program waits for the first alarm to "ring" to start the second one.
How can I run two alarms at the same time ? Thanks for taking time reading this. (OSX Sierra, Xcode 8.2)
main.cpp
using namespace std;
int main(int argc, const char * argv[]) {
Alarm test(12, 12, "foo");
test.start();
Alarm.hpp
class Alarm {
public:
Alarm(int hour, int minute, std::string speech);
void start();
void stop();
bool isStopped() const;
std::string getStats() const;
private:
int m_hour;
int m_minute;
std::string m_speech;
bool m_stopped;
};
Alarm.cpp
using namespace std;
Alarm::Alarm(int hour, int minute, string speech) {
m_hour = hour;
m_minute = minute;
m_speech = speech;
m_stopped = false;
}
void Alarm::start() {
int currentHour, currentMinute;
while (!Alarm::isStopped()) {
time_t now = time(NULL);
struct tm *current = localtime(&now);
currentHour = current->tm_hour;
currentMinute = current->tm_min;
if (currentHour == m_hour && currentMinute == m_minute) {
cout << m_speech << endl;
m_stopped = true;
}
else {
this_thread::sleep_for(chrono::milliseconds(60000));
}
}
}
void Alarm::stop() {
m_stopped = true;
}
bool Alarm::isStopped() const {
return m_stopped;
}