In the following code, I haven’;t used any “threads”. Will creating multiple instances still be a problem? If I use threads, then since threads share the address space – the functioning may get currupted.
Of course there isn’t any “need” to create multiple objects, but I do so (the way I have done it here) will that be a problem?
#include <iostream>
using namespace std;
class boiler
{
private:
// Non static variables can't be initialized inside a class.
bool boilerEmpty;
bool mixtureBoiled;
public:
boiler ()
{
boilerEmpty = true;
mixtureBoiled = false;
}
void fillBoiler()
{
if (boilerEmpty == true)
{
cout << "\nFill boiler.";
boilerEmpty = false;
}
}
void boilMixture ()
{
if ((boilerEmpty == false) && (mixtureBoiled == false))
{
cout << "\nBoil mixture";
mixtureBoiled = true;
}
}
void drainMixture ()
{
if ((boilerEmpty == false) && (mixtureBoiled == true))
{
cout << "\nDrain mixture.";
boilerEmpty = true;
}
}
};
int main ()
{
boiler b, c;
b.fillBoiler ();
b.boilMixture ();
b.drainMixture ();
c.fillBoiler ();
c.boilMixture ();
c.drainMixture ();
}
If you only use an instance from one thread, then having many instances will cause you no problems. The only way that you invite inconsistent behaviour is by trying to use one instance in multiple threads.
If you do use one instance in multiple threads, you will want to investigate using a mutex semaphore to ensure that the instance is being used in only one thread at a time.