Search code examples
c++assertcorrectness

Simple assert for ordered non re-entrant calling?


I have two functions:

void prepare() and void finish() that will be called sequentially like:

prepare();
<do something>;
finish(); 
... 
prepare(); 
<do something>; 
finish();

I want to make a simple assertion to simply test that they are in fact being called this way and that they aren't being called concurrently or out-of-order in the application.

This application is a single-threaded application. This is a simple development/testing sanity check to make sure that these functions are being called in-order and that for whatever reason, they aren't being called concurrently. Furthermore, these assertions/sanity checks should be omitted from production code as performance is crucial!

would a simple assert() like this work best?

int test = 0;

void prepare() {
   assert(++test == 1);

   .
   .
   .
}

void finish() {
    assert(--test == 0);

    .
    .
    .
}

Solution

  • Your code is OK, unless you need to allow nesting prepare and finish calls.

    If nesting is not allowed, you could use a bool instead of an int:

    bool locked = false;;
    
    void prepare() {
        assert( ! locked );
        locked = true;
        ...
    }
    
    void finish() {
        assert( locked );
        locked = false;
        ...
    }