home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / oper_sys / presto / prest_04.lha / src / atomic_int.h next >
Encoding:
C/C++ Source or Header  |  1989-06-06  |  1.5 KB  |  76 lines

  1. //
  2. // Atomic ints are good for counters, etc...  All integer operations
  3. // on them are defined.
  4. //
  5. //
  6.  
  7.  
  8. //
  9. // Binary op
  10. //
  11. //
  12. // return the value at the time of the lock
  13. // acquisition
  14. //
  15. #define AIOP(op)\
  16.     int operator/**/op/**/(int x)    \
  17.     {register int tmp;ai_lock.lock();tmp = ai_val op x;ai_lock.unlock();return tmp;}
  18.  
  19. // 
  20. // Unary op
  21. //
  22. #define AIUNOP(op)\
  23.     int operator/**/op/**/()    \
  24.     {register int tmp;ai_lock.lock();tmp = ai_val/**/op;ai_lock.unlock();return tmp;}
  25.  
  26.  
  27.  
  28.  
  29. class AtomicInt    {
  30.     int         ai_val;
  31.     Spinlock    ai_lock;
  32. public:
  33.     AtomicInt()
  34.         { ai_val = 0; }
  35.     AtomicInt(int x)
  36.         { ai_val = x; }
  37.     AtomicInt(AtomicInt& x)        // should we lock x?
  38.         { ai_val = x.ai_val;}
  39.     ~AtomicInt()
  40.         { ai_lock.unlock(); }
  41.     operator int()
  42.         { return ai_val; }    // we should probably get locked
  43.     void lock()
  44.         { ai_lock.lock(); }    // Careful....
  45.     void unlock()
  46.         { ai_lock.unlock(); }
  47.     int&    val()            // use at your own risk
  48.         { return ai_val; }
  49.     AIOP(=)
  50.     AIOP(+=)
  51.     AIOP(*=)
  52.     AIOP(/=)    
  53.     AIOP(%=)
  54.     AIOP(^=)
  55.     AIOP(&=)
  56.     AIOP(|=)
  57.     AIOP(<<=)
  58.     AIOP(>>=)
  59.     AIUNOP(++)        /* pre inc only */
  60.     AIUNOP(--)        /* post inc only */
  61.     int    preinc()
  62.         {register int tmp; ai_lock.lock();
  63.          tmp = ++ai_val; ai_lock.unlock(); return tmp;}
  64.     int    postinc()
  65.         {register int tmp; ai_lock.lock();
  66.          tmp = ai_val++; ai_lock.unlock(); return tmp;}
  67.     int    predec()
  68.         {register int tmp; ai_lock.lock();
  69.          tmp = --ai_val; ai_lock.unlock(); return tmp;}
  70.     int    postdec()
  71.         {register int tmp; ai_lock.lock();
  72.          tmp = ai_val--; ai_lock.unlock(); return tmp;}         
  73.     // Should probably have the rest of the operators here too...
  74. };
  75.  
  76.