开发者

Creating a mutex like program using CriticalSection

开发者 https://www.devze.com 2023-02-25 00:51 出处:网络
e.g. EnterCriticalSection ( cs ); LeaveCriticalSection ( cs ); I want to create a functi开发者_StackOverflow社区on locking it and release if invoke your function call or leave the object.

e.g.

EnterCriticalSection ( cs );
LeaveCriticalSection ( cs );

I want to create a functi开发者_StackOverflow社区on locking it and release if invoke your function call or leave the object.

How can get started to work out the class?


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.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消