I need a thread-safe counter that won't block the thread. (For pre-C11 tools.) Locking a mutex around ++/-- operations can block it. So I came up with this, using semaphores. Is it sensible?
#include <semaphore.h>
class AtomicCounter {
public:
AtomicCounter(unsigned int i=0) { sem_init(&m, 0, i); }
~AtomicCounter() { sem_destroy(&m); }
operator unsigned int() { int a; sem_getvalue(&m, &a); return a; }
AtomicCounter& operator++() { sem_post(&m); return *this; }
AtomicCounter& operator--() { sem_trywait(&m); return *this; }
private:
AtomicCounter(const AtomicCounter&);
AtomicCounter& operator=(const AtomicCounter&);
sem_t m;
};
EDIT An alternative would need to support ARMv7 and x86 and work with any common compiler.
I regularly use an adaptation of the method described by Golubenco & Sarbu to solve this problem.
This works with gcc; I have only tried this on x84 and amd64 architectures.
Essentially, you declare some counter macros, or inline functions if C++, that use the compiler provided intrinsic functions for safe multi-thread / multi-core increment, decrement and test.
It doesn't quite have pure C++ semantics, which is OK in my use case because I have code shared between C and C++, but it wouldn't be a lot of effort to incorporate into your class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.