首页 > 解决方案 > 如何初始化已经在 C++ 中声明的唯一锁?

问题描述

我创建了一个类,并将一组唯一锁和一组互斥锁声明为私有变量。我的问题是如何在类的构造函数中连接它们两者?

头文件:

#include <iostream>
#include <mutex>
#include <string>

#define PHILO_NUM 5
class philosophers
{
private:
    std::mutex _mu[5];
    std::unique_lock<std::mutex> _fork[5], _screen;
    std::mutex _screenMutex;
public:
    philosophers();
};

c++ 文件:

#include "philosophers .h"

philosophers::philosophers()
{
    for (int i = 0; i < PHILO_NUM; i++)
    {
        // Somehow connect this->_forks[i] and this->_mu[i]
    }
// At the end connect this->_screen and this->_screenMutex
}

标签: c++dining-philosopher

解决方案


说你应该做什么并不容易,因为你不说你想做什么。我认为您混合了锁和互斥锁。没有理由共享锁(正如您在此处尝试所做的那样)。您需要共享互斥锁,但一个互斥锁可以与任意多个std::unique_locks关联(但其中只有一个可以同时锁定互斥锁)。

因此,我将按如下方式实现您的课程:

#include <mutex>

constexpr size_t PHILO_NUM = 5;
class philosophers
{
private:
    std::mutex _mu[PHILO_NUM];
    std::mutex _screenMutex;
public:
    philosophers() = default; // Nothing to do here
 
    std::unique_lock grab_fork(size_t index) {
        return std::unique_lock (_mu[index]);
    }
};

因此,如果有人抓住叉子,只要他们持有该叉子的锁,他们就可以使用它。示例用法如下所示:

philosophers p;
void eat() {
    auto lock = p.grab_fork(3);
    // Now I can eat
    lock.unlock(); // Not really necessary, lock will release the mutex, when it is destroyed at the end of the scope
}

推荐阅读