[英]Posix Semaphore as a Thread-Safe Counter
I need a thread-safe counter that won't block the thread. 我需要一个不会阻塞线程的线程安全计数器。 (For pre-C11 tools.) Locking a mutex around ++/-- operations can block it. (对于C11之前的工具。)将互斥锁锁定在++ /-操作周围可能会阻止它。 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. 编辑一个替代方案将需要支持ARMv7和x86并与任何常见的编译器一起使用。
I regularly use an adaptation of the method described by Golubenco & Sarbu to solve this problem. 我经常使用Golubenco&Sarbu描述的方法的改编来解决此问题。
This works with gcc; 这适用于gcc; I have only tried this on x84 and amd64 architectures. 我只在x84和amd64体系结构上进行过尝试。
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. 本质上,您声明了一些计数器宏,或者使用C ++的内联函数,这些宏使用编译器提供的内在函数进行安全的多线程/多核递增,递减和测试。
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. 它没有完全的C ++语义,这在我的用例中还可以,因为我在C和C ++之间共享了代码,但是并不需要花费很多精力将它纳入您的类中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.