I have created a C++ class named Timer, it has 3 methods:
- start()
- stop()
- print()
The start()
method, enables a flag named run
, setting its value to true
.
The stop()
method, disable the flag, setting its value to false
.
The print()
method, executes a while()
under condition if run == true
, and print some text sleeping a half second.
Timer.hpp
#ifndef TIMER
#define TIMER 1
#include <iostream>
#include <cstdbool>
#include <unistd.h>
class Timer{
private:
bool run;
public:
void start();
void stop();
void print();
};
#endif
Timer.cpp
#include "Timer.hpp"
void Timer::start(){
this->run = true;
this->print();
return;
}
void Timer::stop(){
this->run = false;
return;
}
void Timer::print(){
int counter = 0;
while(this->run == true){
std::cout << counter << std::endl;
counter++;
usleep(500000);
}
return;
}
main.cpp
#include <pthread.h>
#include "Timer.hpp"
void *handler(void *argument){
((Timer *) argument)->start();
return argument;
}
int main(void){
Timer *timer = new Timer();
pthread_t timer_thread;
int mainCounter = 0;
pthread_create(&timer_thread, NULL, handler, (void *) &timer);
while(true){
if(mainCounter == 100){
std::cout << "Stopping..." << std::endl;
timer->stop();
}
std::cout << " => " << mainCounter << std::endl;
mainCounter++;
usleep(50000);
}
return 0;
}
My problem.
I've created a thread to handle the execution of method start()
, after I've created a condition inside main thread in which after mainCounter
get 100 iterations, it executes timer->stop()
, but it doesn't stop the timer loop.
When mainCounter
arrives to 100th iteration, it can't stop the loop inside thread.
The instruction to compile is:
g++ Timer.cpp -c
g++ Timer.cpp main.cpp -o main -lpthread
The output is:
9
=> 90
=> 91
=> 92
=> 93
=> 94
=> 95
=> 96
=> 97
=> 98
=> 99
10
Stopping...
=> 100
=> 101
=> 102
=> 103
=> 104
=> 105
=> 106
=> 107
=> 108
=> 109
11