Testing locklessness C++

86 Views Asked by At

Is there any way to detect whether a function or thread is blocking? I want to build a test case in which I can test whether a function is hard realtime-safe.

2

There are 2 best solutions below

0
On

No. There is no general way to do this.

There are many ways to 'block' such as a spin-lock and similar 'try-fail-retry' algorithms that there's no realistic way to instrument what code 'blocks'.

Look at something like a sequential lock. That's a lock that never blocks a (single) writer but causes readers to re-try if they make have made a read during a write (and so may have read a corrupt value).

It scales in readers really well particularly if writes are relatively infrequent. Certainly the important point being readers don't block each other so the delay on reads is a fixed value as readers scale.

It's debatable whether it's technically lock-free and surely impossible to write a tool to analyse the algorithm and determine if it is lock-free or at what point it is (logically) blocking.

0
On

No, it is not possible. Consider this function:

unsigned compute(unsigned x)
{
    while (x < 10) {
        if (x) {
            x++;
        }
    }
    return x;
}

It will run in bounded time, unless x is zero in which case it will take infinite time.

You cannot determine whether such functions exist in your program, because of the Halting Problem.

If you only need to determine whether your program calls specific system functions that you have determined to be blocking, such as network I/O, you can do that by interposing (via LD_PRELOAD, -fwrap or similar linking tricks) wrapper functions around those restricted system functions. For example you could write a wrapper for recv() which will check that the file descriptor is non-blocking, and return EINVAL otherwise.

Note that on many systems, disk I/O is fundamentally a blocking operation, so you'll need to disable that entirely.