c++ - 如何初始化已经在 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
}
解决方案
说你应该做什么并不容易,因为你不说你想做什么。我认为您混合了锁和互斥锁。没有理由共享锁(正如您在此处尝试所做的那样)。您需要共享互斥锁,但一个互斥锁可以与任意多个std::unique_lock
s关联(但其中只有一个可以同时锁定互斥锁)。
因此,我将按如下方式实现您的课程:
#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
}
推荐阅读
- flutter - 设置项目计数 ListView.builder 预先创建和滚动时
- r - 使用特定的结束日期 01/01/1998 将生日转换为年龄
- rust - 使用“cargo rustc -- -o 文件名”构建时从输出文件名中省略哈希可能吗?
- svm - LinearRegression 类和参数 kernel='Linear' 的支持向量机(SVM)类有什么区别?
- blockchain - 以太坊签名交易原始的正则表达式验证
- boolean-logic - 给定 n 个布尔变量,如何仅通过命题演算来检查其中 k 个或更少的变量是否为真?
- python - Python中的参数方程问题
- elasticsearch-6 - 为什么我不应该轻松实现类似于 Elasticsearch 的父子的 join 数据类型关系
- python - 如何在 sanic 中记录所有传入请求和对所有 api 的出站响应
- mysql - Django 项目不适用于 MySql 数据库