c++multithreadingvisual-c++booleancritical-section

Setting a default value for a bool


I am working on a Queue class using threads in C++ (Windows 10 Visual Studio).

In my constructor, I start by setting a boolean error value to false. Immediately after, I attempt to initialise the critical section. If the there is a problem, the bool is set to true, otherwise it stays as false. I check this value in the main function (not shown) and end the program if the crit sec is not initialised (bool is false).

Constructor code:

Queue() {
        // ERROR_CRIT is bool: false = no error in initialising crit section, true = there is an error
        ERROR_CRIT = false;
        // check init 
        if (!InitializeCriticalSectionAndSpinCount(&CritSec, 0x00000400)) {
            ERROR_INIT_CRIT_SEC = true;
        }
        totalCustomers = 0;
        currentReadIndex = 0;
        currentWriteIndex = 0;
        customerNum = 0;
    };

My question is: what types of booleans should I have default set to true or false ? I have thought about this many times while writing other programs and I am not sure when to set a default value for a bool unless it is obvious. Sometimes it seems fair to start with either value. I feel it would be strange to set an error bool to start as true, but starting it as false also may be strange.

In the real world or in a company, would I remove the line 3 and add an else statement to the if with else {ERROR_CRIT = false;} ? Would this improve readability ? This is probably preference but what is often seen in the real world programming ?

Thank you in advance :D


Solution

  • A much better approach is to prevent the queue from existing at all if the critical section cannot be created. This establishes a tighter class invariant for the Queue class, which simplifies its implementation.

    This is done by throwing an exception:

    Queue() {
        // check init 
        if (!InitializeCriticalSectionAndSpinCount(&CritSec, 0x00000400)) {
            throw std::runtime_error("failed to create the critical section");
        }
        totalCustomers = 0;
        currentReadIndex = 0;
        currentWriteIndex = 0;
        customerNum = 0;
    };
    

    This way, you don't ever need to check for ERROR_CRIT, since the Queue existing is enough information to guarantee that the critical section is correctly initialized.