In the multi-threaded environment to count, you need to ensure that the consistency of the count variables and thread safety to ensure that the count is correct in multi-threaded environment.
The atomic count is the feature that provides this requirement, which guarantees that the count operation will never be interrupted by any other practice or event when it is completed, and the following is an atomic counter for pthreads
Cons: When you use locks to implement atomic counts, the lock operation is much more expensive than the counter plus and minus operations, and you can see which operations consume more by using the perf command from the Linux-based performance instrumentation tool.
#ifndef __atomiccounter_h__#define __atomiccounter_h__#if defined (__linux__)//catomiccounter.h for Pthreads#include <pthread.h>class catomiccounter {private:class Cguard//pthread_mutex_t lock Guardian class Cguard{public:cguard (Pthread_ Mutex_t & Mutex): M_mutex (Mutex) {pthread_mutex_lock (&m_mutex);} ~cguard () {pthread_mutex_unlock (&m_mutex);} Private:pthread_mutex_tm_mutex;}; Private:catomiccounter (Catomiccounter const&);//Prohibit copy construction catomiccounter& operator= (catomiccounter const& );//Prohibit assignment construction public:///needs to be displayed call this constructor to prevent the compiler from using the default constructor provided by explicit Catomiccounter (long N): m_cnt (n) {pthread_mutex_init ( &m_mutex, 0);} ~catomiccounter () {Pthread_mutex_destroy (&m_mutex);} Long operator++ () {Cguard Guard (M_mutex); return ++m_cnt;} Long operator--() {Cguard Guard (M_mutex); return--m_cnt;} Operator long () Const{cguard Guard (M_mutex); return m_cnt;} private://if no mutable,operator long () const compilation fails//CONST member function operator long () the value of the variable cannot be modified//its first line Cguard guard (M_mutex); The entry requirements for the non-const type//If the M_mutex is declared as a mutable type, it can be placedThe non-const member function///Cannot modify the properties of the variable,//so that M_mutex through the mutable of the modifier to get rid of the const member function can be used as not const variable as a guard () argument mutable pthread_mutex_t m_ Mutex longm_cnt;}; #endif//#if defined (__linux__) #endif
Usage Test Cases:
#include "AtomicCounter.h" #include <iostream>using namespace Std;int main () {Catomiccounter atomic (1); ++atomic; cout<<__file__<< ":" <<__LINE__<< ":" <<__FUNCTION__<< (Long) Atomic<<endl ;--atomic;cout<<__file__<< ":" <<__LINE__<< ":" <<__FUNCTION__<< (long) atomic <<endl;}
Multithreaded Test Cases:
(END)
Atomic counter for Pthreads