Question

Currently in my code I have sections such as this

boost::mutex Mymutex

void methodA()
{
   boost::mutex::scoped_lock lock(Mymutex);
   ......
   ......
   ......
}

I read that critical sections are faster than a mutex ? So I am doing something like this I wanted to know if this is faster.

 boost::recursive_mutex m_guard;
 void methodA()
 {
       // this section is not locked
      {
          boost::lock_guard<boost::recursive_mutex> lock(m_guard);
         // this section is locked
      }
      //This section not locked
 }    

Is the second method faster ? The reason I am mostly using mutex is to prevent race conditions and lock access to methods so that one thread accesses it at a time. Is there anything faster than that ? My other concern was on the statement

  boost::lock_guard<boost::recursive_mutex> lock(m_guard);

it seems that everytime methodA() would be called lock would be created on the stack. I was thinking about declaring lock as a static variable so it does not get created on the stack everytime this method is called.In that case how can I add m_guard to it. For instance

 boost::recursive_mutex SomeClass::m_guard; //This is static 
 boost::lock_guard<boost::recursive_mutex> SomeClass::lock //Suppose this is static
 void SomeClass::methodA()
 {

      {
         //How do i make lock "lock" mguard 

      }

 }    
Was it helpful?

Solution

Is there anything faster than that ?

If busy-wait is appropriate in your case, you can try to use spinlock implemented on top of boost::atomic_flag.

SO: When should one use a spinlock instead of mutex?

class spinlock
{
    atomic_flag flag = ATOMIC_FLAG_INIT;
public:
    void lock()
    {
        while(flag.test_and_set(memory_order_acquire));
    }
    void unlock()
    {
        flag.clear(memory_order_release);
    }
};

void foo()
{
    static spinlock lock;
    lock_guard<spinlock> guard(lock);
    // do job
}

boost::lock_guard<boost::recursive_mutex> lock(m_guard); it seems that everytime methodA() would be called lock would be created on the stack.

It is not lock, it is just RAII wrapper, which locks mutex in constructor and releases it in destructor. It is OK, to create lock_guard on stack.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top