3

I am trying to make it clear for myself what "interlocked" exactly means. I read the following: "The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. They also perform operations on variables in an atomic manner."

So could the following functions be called interlocked?

#include <QtCore>
#include <QAtomicPointer>

QAtomicInt i;

void interlockedMultiply(int factor)
{
    int oldValue;
    do
    {
        oldValue = i;
    } while (!i.testAndSetOrdered(oldValue, oldValue * factor));
}


long long x;
QReadWriteLock lock;

void interlockedAdd(long long y)
{
    lock.lockForWrite();
    x += y;
    lock.unlock();
}

If no, suggest a proper name, please.

mentalmushroom
  • 2,261
  • 1
  • 26
  • 34
  • 1
    `Interlocked` doesn't really mean anything too specific, in my experience (I may be wrong, though). It's more of a label applied to utility functions that wrap atomic primitives. So yes, I'd say it's fine to label these functions "interlocked", although perhaps using a lock in such a function is surprising. – Cameron Mar 29 '16 at 14:33

2 Answers2

1

Interlocked means that concurrent operations will yield the expected result. I.e. if you perform an interlocked addition five times, the variable will have been incremented five times. Not more, and not less.

Sven Nilsson
  • 1,861
  • 10
  • 11
  • Both of the above functions follow this rule. So can we call them interlocked? I am especially curious about the one with a critical section, as interlocked operations are often used as an alternative to blocking operations, i.e. locks. – mentalmushroom Mar 29 '16 at 14:44
  • Even an atomic operation can use locks. – knivil Mar 29 '16 at 15:17
0

It's not deceptive to name these functions as such, but you should still document their semantics, preferably using some sort of a formal description that supports concurrency primitives.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313