See what's going on with flipcode!

This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.


  Safe Multi-threaded Long
  Submitted by

When accessing a long number in a multithreaded environment the number needed to be safe from being accessed at exactly same time and by that corrupting it. Windows provides various APIs for multithreaded environment, part of them are InterlockedIncrement/Decrement/... The provided SafeLong class gives you the ability to work with a long number in a multithreaded environment without the worries. Most of the operators are overloaded to support comparison with another SafeLong or with a normal long number. Enjoy Nir Dremer

Download Associated File: SafeLong.h (2,101 bytes)

/// This is a wrapper for the InterLocked... Windows APIs.
/// Instead of using then you can instantiate this class and work with it
/// as a normal long number. 
//  All operations will safe for multithreaded access.
#include <windows.h>

class SafeLong { public: SafeLong(void) { InterlockedExchange(&m_value, 0); }; ~SafeLong(void) {};

SafeLong& operator+=(const SafeLong &_Right) { InterlockedExchangeAdd(&m_value, _Right.m_value); return *this; }

SafeLong& operator-=(const SafeLong &_Right) { InterlockedExchange(&m_value, m_value - _Right.m_value); return *this; } SafeLong& operator=(const SafeLong &_Right) { InterlockedExchange(&m_value, _Right.m_value); return *this; }

SafeLong& operator+=(const long _Right) { InterlockedExchangeAdd(&m_value, _Right); return *this; }

SafeLong& operator-=(const long _Right) { InterlockedExchange(&m_value, m_value - _Right); return *this; }

SafeLong& operator=(const long _Right) { InterlockedExchange(&m_value, _Right); return *this; }

bool operator==(const SafeLong &_Right) { return m_value == _Right.m_value; }

bool operator!=(const SafeLong &_Right) { return !(m_value == _Right.m_value); }

bool operator==(const long _Right) { return m_value == _Right; }

bool operator!=(const long _Right) { return !(m_value == _Right); }

operator long() { return m_value; }

operator bool() { return m_value ? true : false; }

SafeLong& operator++(int pos) { if (pos == 0) { InterlockedIncrement(&m_value); } else { InterlockedExchangeAdd(&m_value, pos+1); } return *this; }

SafeLong& operator--(int pos) { if (pos == 0) { InterlockedDecrement(&m_value); } else { InterlockedExchangeAdd(&m_value, - (pos+1)); } return *this; } private: long m_value; };


The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.


Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.