lundi 3 septembre 2018

Why creating thread in constructor results in runtime error

I have following code in C++, I am trying to spawn new thread from the constructor of a class. I get run time error. I do not understand why, and how could it be prevented. I am quite newbie in C++. In VS2017, it errors in abort() has been called.

#include <iostream>
#include <thread>
#include <chrono>

class Rectangle {
public:
    int area(void);
    Rectangle();
    ~Rectangle();

private:
    int x, y;
    int UpdateData();
};

Rectangle::Rectangle() {
    x = 1;
    y = 2;
    std::thread modelThread(&Rectangle::UpdateData, this);
}

Rectangle::~Rectangle() {
}
int Rectangle::area() {
    return x * y;
}
int Rectangle::UpdateData()
{
    while (true) {
        x++;
        y += 2;
        std::cout << "Area with x:" << x << " y:" << y << " area:" << Rectangle::area() << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(2000));
    }
    return 0;
}

int main() {
    Rectangle rect;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire