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.

 

  Java-like Monitor Macro For C++
  Submitted by



The attached code shows how to do a macro that works like the monitor statement in Java.

The macro can be used in two ways:

monitor(0) {
	//Code here is protected by a mutex
	//and is run only by one thread at a time.
}

monitor(mutexobject) { //Code here is protected by the mutex object given to the macro }



This macro prevents unlocked mutexes to be left around, since the mutex is unlocked when the statement after the macro is left (wether by flowing out, returning from function, goto, exception, etc.)

Macros can also be nested if the mutex class supports nesting.

Monitor.h:
#ifndef _MONITOR_H_
#define _MONITOR_H_

#ifndef MUTEXCLASS

namespace MutexMonitor {

class Mutex { public: void lock() {}; void unlock() {}; };

} //MutexMonitor #define MUTEXCLASS MutexMonitor::Mutex #endif

struct MutexMonitorClass {

MUTEXCLASS *mutex; int state;

inline MutexMonitorClass() { state=0; mutex=0; }

inline ~MutexMonitorClass() {if (mutex) mutex-unlock();}; };

MUTEXCLASS mutexmonitormutex;

namespace MutexMonitor {

inline MUTEXCLASS * cast2mutex(const int V) { return (MUTEXCLASS*)0; }; inline MUTEXCLASS * cast2mutex(MUTEXCLASS * V) { return V; };

};

#define monitor(mvar) \ for(MutexMonitorClass mutexmonitor; \ mutexmonitor.state<2; \ mutexmonitor.state++) \ \ if (mutexmonitor.state==0) \ { \ if ((mvar)!=0) { \ mutexmonitor.mutex=MutexMonitor::cast2mutex(mvar); \ MutexMonitor::cast2mutex(mvar)-lock(); \ } else { \ static MUTEXCLASS * mutex; \ static bool firsttime=true; \ if (firsttime) { \ mutexmonitormutex.lock(); \ static MUTEXCLASS smutex; /* Complier makes sure that static */\ mutexmonitormutex.unlock(); /* vars are initialized once */\ mutex=&smutex; /* We make sure that only one thread */\ firsttime=false; /* can attempt initialization at a time */\ } \ mutexmonitor.mutex=mutex; \ mutex-lock(); \ }; \ } else

#endif //_MONITOR_H_

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.