| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
#ifndef __KIS_LOCK_FREE_LOD_COUNTER_H |
| 8 |
#define __KIS_LOCK_FREE_LOD_COUNTER_H |
| 9 |
|
| 10 |
#include <QAtomicInt> |
| 11 |
|
| 12 |
|
| 13 |
class KisLockFreeLodCounter |
| 14 |
{ |
| 15 |
public: |
| 16 |
void addLod(int newLod) { |
| 17 |
int oldValue = 0; |
| 18 |
int newValue = 0; |
| 19 |
|
| 20 |
do { |
| 21 |
oldValue = m_num; |
| 22 |
|
| 23 |
int counter; |
| 24 |
int lod; |
| 25 |
unpackLod(oldValue, &counter, &lod); |
| 26 |
|
| 27 |
if (!counter) { |
| 28 |
lod = newLod; |
| 29 |
} else { |
| 30 |
Q_ASSERT(lod == newLod); |
| 31 |
} |
| 32 |
|
| 33 |
counter++; |
| 34 |
newValue = packLod(counter, lod); |
| 35 |
} while(!m_num.testAndSetOrdered(oldValue, newValue)); |
| 36 |
} |
| 37 |
|
| 38 |
void removeLod() { |
| 39 |
int oldValue = 0; |
| 40 |
int newValue = 0; |
| 41 |
|
| 42 |
do { |
| 43 |
oldValue = m_num; |
| 44 |
|
| 45 |
int counter; |
| 46 |
int lod; |
| 47 |
unpackLod(oldValue, &counter, &lod); |
| 48 |
|
| 49 |
Q_ASSERT(counter > 0); |
| 50 |
|
| 51 |
counter--; |
| 52 |
newValue = packLod(counter, lod); |
| 53 |
} while(!m_num.testAndSetOrdered(oldValue, newValue)); |
| 54 |
} |
| 55 |
|
| 56 |
int readLod() const { |
| 57 |
int value = m_num; |
| 58 |
|
| 59 |
int counter; |
| 60 |
int lod; |
| 61 |
unpackLod(value, &counter, &lod); |
| 62 |
|
| 63 |
return counter ? lod : -1; |
| 64 |
} |
| 65 |
|
| 66 |
void testingClear() { |
| 67 |
m_num = 0; |
| 68 |
} |
| 69 |
|
| 70 |
private: |
| 71 |
static inline int packLod(int counter, int lod) { |
| 72 |
return (counter << 8) | (lod & 0xFF); |
| 73 |
} |
| 74 |
|
| 75 |
static inline void unpackLod(int value, int *counter, int *lod) { |
| 76 |
*lod = value & 0xFF; |
| 77 |
*counter = value >> 8; |
| 78 |
} |
| 79 |
|
| 80 |
private: |
| 81 |
QAtomicInt m_num; |
| 82 |
}; |
| 83 |
|
| 84 |
#endif |