Mnop492
Mnop492

Reputation: 53

Creating a mutex like program using CriticalSection

e.g.

EnterCriticalSection ( cs );
LeaveCriticalSection ( cs );

I want to create a function locking it and release if invoke your function call or leave the object.

How can get started to work out the class?

Upvotes: 1

Views: 758

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385134

So a scoped CriticalSection?

class ScopedCriticalSection {
   CRITICAL_SECTION cs;

   ScopedCriticalSection()
   {
      if (!InitializeCriticalSectionAndSpinCount(&cs, 0x00000400))
         throw std::runtime_error("Could not initialise CriticalSection object");
      EnterCriticalSection(&cs);
   }

   ~ScopedCriticalSection()
   {
      LeaveCriticalSection(&cs);
      DeleteCriticalSection(&cs);
   }
};

void foo()
{
   ScopedCriticalSection scs;

   /* code! */
}

Or consider a Boost mutex.

Upvotes: 2

Jonas Bötel
Jonas Bötel

Reputation: 4482

You could wrap the critical section in a Mutex class with public functions acquire and release and have a second class called ScopedLock acquire the mutex on construction and release it on destruction.

The Mutex:

class Mutex {
   public:
     Mutex() {
       //TODO: create cs
     }
     ~Mutex() {
       //TODO: destroy cs
     }
     void acquire() {
       EnterCriticalSection(cs);
     }
     void release() {
       LeaveCriticalSection(cs);
     }
   private:
     LPCRITICAL_SECTION cs;
     Mutex(const Mutex&); //non-copyable
     Mutex& operator=(const Mutex&); //non-assignable
};

The Lock:

class ScopedLock {
  public:
    ScopedLock(Mutex* mutex_) : mutex(mutex_) {
      mutex->acquire();
    }
    ~ScopedLock() {
      mutex->release();
    }
  private:
    Mutex* mutex;
};

Use it like this:

Mutex someMutex;

void foo() {
  ScopedLock lock(&someMutex);
  //critical stuff here
}

void bar() {
  ScopedLock lock(&someMutex);
  //other critical stuff here
}

Upvotes: 1

Related Questions