c++ - 范围互斥锁的自定义 RAII C++ 实现

标签 c++ linux pthreads mutex raii

我不能使用 boost 或最新的 std::thread 库。要走的路是创建一个范围互斥体的自定义实现。

一句话,当一个类实例被创建一个互斥锁。在类销毁时,互斥锁被解锁。

任何可用的实现?我不想重新发明轮子。

我需要使用 pthreads。

  • 资源获取是初始化 == “RAII”

最佳答案

Note This is an old answer. C++11 contains better helpers that are more platform independent:

And other options like std::unique_lock, boost::unique_lock

任何 RAII 教程都可以。

这里是要点:(也在 http://ideone.com/kkB86 上)

// stub mutex_t: implement this for your operating system
struct mutex_t 
{ 
    void Acquire() {} 
    void Release() {} 
};

struct LockGuard
{
     LockGuard(mutex_t& mutex) : _ref(mutex) 
     { 
         _ref.Acquire();  // TODO operating system specific
     }

     ~LockGuard() 
     { 
          _ref.Release(); // TODO operating system specific
     }
   private:
     LockGuard(const LockGuard&); // or use c++0x ` = delete`

     mutex_t& _ref;
};

int main()
{
    mutex_t mtx;

    {
        LockGuard lock(mtx);
        // LockGuard copy(lock); // ERROR: constructor private
        // lock = LockGuard(mtx);// ERROR: no default assignment operator
    }

}

当然你可以让它对 mutex_t 通用,你可以防止子类化。 由于引用字段,已禁止复制/分配

编辑对于 pthread:

struct mutex_t
{
    public:
        mutex_t(pthread_mutex_t &lock) : m_mutex(lock) {}

        void Acquire() { pthread_mutex_lock(&m_mutex);   }
        void Release() { pthread_mutex_unlock(&m_mutex); }
    private:
        pthread_mutex_t& m_mutex;
};

关于c++ - 范围互斥锁的自定义 RAII C++ 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7977255/

相关文章:

c - 线程具有相同的 id

c++ - Windows/Winsock UDP 数据包被分组在一起?

c++ - 如何使用可变数量的 std::string_view 参数正确实现函数?

c++ - 在 C++ 中调用 main() 本身?

c++ - 您可以将临时对象传递给通过引用获取变量的函数吗?

python - 在 Python 脚本中打印数字总和

c++ - 如何解决 Linux 上的线程问题?

在纯c中,在线程中更改数组/结构/..的部分而不阻塞整个事情

ruby - 找不到 gem 命令

linux - 使用 xargs 将变量传递给别名命令