Main Page | Namespace List | Class Hierarchy | Compound List | File List | Namespace Members | Compound Members | File Members | Related Pages

GuardedVariable.hpp

Go to the documentation of this file.
00001 #ifndef GuardedVariable_HPP
00002 #define GuardedVariable_HPP
00003 
00004 #include <iostream>
00005 
00006 using namespace std;
00007 
00008 #include <pthread.h>
00009 
00020   template<typename T>
00021   class GuardedVariable{
00022 
00023     private:
00024 
00025       volatile T variable; 
00026       pthread_mutex_t lock;
00028     public:
00029 
00035       GuardedVariable(T initialValue=0)
00036                    :variable(initialValue){
00037 
00038         pthread_mutex_init(&lock, NULL);
00039 
00040       }
00041 
00047       T inc(){
00048 
00049         T tmp;
00050         pthread_mutex_lock(&lock);
00051         tmp = variable++;
00052         pthread_mutex_unlock(&lock);
00053         return tmp;
00054 
00055       }
00056       
00062       T dec(){
00063 
00064         T tmp;
00065         pthread_mutex_lock(&lock);
00066         tmp = variable--;
00067         pthread_mutex_unlock(&lock);
00068         return tmp;
00069 
00070       }
00071 
00075       T value(){
00076 
00077         T tmp;
00078         pthread_mutex_lock(&lock);
00079         tmp = variable;
00080         pthread_mutex_unlock(&lock);
00081         return tmp;
00082 
00083       }
00084       
00090       void set(T newValue){
00091          pthread_mutex_lock(&lock);
00092           variable = newValue;
00093         pthread_mutex_unlock(&lock);
00094       }
00095 
00096 
00100       void reset(){
00101         set(0);
00102       }
00103 
00104 
00105 
00106   };
00107 
00108 
00109 #endif//GuardedVariable_HPP

Generated on Mon Sep 6 16:12:47 2004 by doxygen 1.3.3