I'm facing a threads problem:
Here is a code to reproduce the error:
using namespace std;
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <math.h>
#include <cstdlib>
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <thread>
#include <vector>
#include "mychrono.hpp"
int main()
{
std::vector<Chronometer*> car_crono;
Chronometer chrono, output_chrono;
std::vector<std::thread> threads;
while (1) {
for(int i = 0; i < 2; i++)
{
car_crono.push_back(new Chronometer);
}
for(int i = 0; i<2; i++)
{
threads.push_back(std::thread(&Chronometer::start_chrono, car_crono[i], std::ref(chrono)));
}
//std::cout << "Threads size: " << threads.size();
for (auto &th : threads) {
th.join();
}
std::cout << "Hello-world" << std::endl;
}
}
My chrono.cpp
#include "mychrono.hpp"
#include <time.h>
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <thread>
//int Chronometer::hour(0), min(0), sec(0);
Chronometer::Chronometer() : hour(0), min(0), sec(0)
{
}
Chronometer& Chronometer::start_chrono(Chronometer& chrono)
{
if(chrono.hour == 0 && chrono.min == 0 && chrono.sec == 0)
{
bool condition = true;
while(condition) {
sleep(1);
chrono.sec++;
if(sec > 59) {
chrono.min++;
chrono.sec = 0;
}
if(min > 59) {
chrono.hour++;
chrono.sec = 0;
chrono.min = 0;
}
if(chrono.sec == 10)
{
condition = false;
}
std::cout << "chrono: " << chrono << std::endl;
}
}
return chrono;
}
My chrono.hpp
#include <time.h>
#include <iostream>
#include <sstream>
#ifndef mychrono_hpp
#define mychrono_hpp
class Chronometer
{
private:
int hour, min, sec;
//std::stringstream ss;
//Chronometer chrono;
public:
Chronometer();
Chronometer& start_chrono(Chronometer& chrono);
Chronometer& finish_chrono(Chronometer& chrono);
friend std::ostream& operator<<(std::ostream& flux, Chronometer t);
Chronometer& operator=(const Chronometer& other);
~Chronometer();
};
#endif
My purpose is just to launch independant several chronometers in background to get the result. For one instantiated Chronometer object the program crash at the end with the following output:
terminate called after throwing an instance of 'std::system_error'
what(): Invalid argument
Abandon (core dumped)
But for 2 chronometers for example, the treads increment one chronometer 2 times faster instead of increment two independent chronometer.
I'm a beginner in threads so I have no idea why is running like that