Fast concurrent counter for 2 threads:
struct ConcurrentCounter {
private: // shm data
unsigned long mCounter_byFirstThread;
char CPU_CACHE_GUARD[PAD_SIZE];
unsigned long mCounter_bySecondThread;
public: // interface for first thread
inline void increment_byFirstThread() { mCounter_byFirstThread++; }
inline void decrement_byFirstThread() { mCounter_byFirstThread--; }
public: // interface for second thread
inline void increment_bySecondThread() { mCounter_bySecondThread++; }
inline void decrement_bySecondThread() { mCounter_bySecondThread--; }
public: // concurrent interface
inline unsigned long getCounter_safe() {
return (mCounter_byFirstThread + mCounter_bySecondThread);
}
public: // init interface
void initCounter_unsafe(unsigned long aValue = 0) {
mCounter_byFirstThread = 0;
mCounter_bySecondThread = 0;
if (0 == aValue) return;
mCounter_byFirstThread = aValue / 2;
mCounter_bySecondThread = aValue - mCounter_byFirstThread;
}
} __attribute__((__packed__));
%%
No comments:
Post a Comment