c++ - 对于这段代码,有什么比升压互斥锁更快的吗?

标签 c++ critical-section boost-mutex

目前在我的代码中有这样的部分

boost::mutex Mymutex

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

我读到临界区比互斥体快?所以我正在做这样的事情我想知道这是否更快。

 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
 }    

第二种方法更快吗?我主要使用互斥锁的原因是为了防止竞争条件并锁定对方法的访问,以便一个线程一次访问它。有什么比这更快的吗?我的另一个担忧是声明

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

似乎每次调用 methodA() 时都会在堆栈上创建锁。 我正在考虑将 lock 声明为静态变量,这样它就不会在每次调用此方法时都在堆栈上创建。在那种情况下,我如何向它添加 m_guard。例如

 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 

      }

 }    

最佳答案

Is there anything faster than that ?

如果busy-wait适用于您的情况,您可以尝试使用 spinlockboost::atomic_flag 之上实现.

所以: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.

它不是锁,它只是 RAII 包装器,它在构造函数中锁定互斥锁并在析构函数中释放它。可以,在堆栈上创建 lock_guard。

关于c++ - 对于这段代码,有什么比升压互斥锁更快的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15939770/

相关文章:

C++ OpenMP 关键 : "one-way" locking?

linux - 公平临界区 (Linux)

c++ - 使用boost将单线程变成多线程

c++ - 资源而不是外部文件 C++

c++ - 在小代码中查找段错误

c++ - 自动创建未知数量的多个 C++ 对象

c++ - 在两个不同的类中使用 Boost mutex

c++ - Eclipse项目中的OSCPack外部库测试用例

multithreading - Delphi线程: CriticalSection not being "Release' d"when using Synchronize inside its method

c++ - 使用 firebreath 插件防止浏览器关闭