[英]How to declare and initialize a vector of semaphores in c++?
Say I have n different resources.假设我有 n 个不同的资源。 Let's say n = 5 as an example, but n can be large and optionally an input value.
假设 n = 5 作为示例,但 n 可以很大并且可以选择输入值。 I want to initialize a vector of n binary semaphores.
我想初始化一个包含 n 个二进制信号量的向量。 How do I do that?
我怎么做?
I believe the problem is because the constructor for binary_semaphore
or counting_semaphore
has been marked explicit
.我相信问题是因为
binary_semaphore
或counting_semaphore
的构造函数已被标记为explicit
。 I've tried the vector constructor for n objects of the same value, and also push_back
and emplace_back
, but nothing seems to work.我已经为 n 个具有相同值的对象以及
push_back
和emplace_back
尝试了向量构造函数,但似乎没有任何效果。 Is there a way to solve this problem?有没有办法解决这个问题?
Semaphores (along with many other mutex-like types... including mutex
) are non-moveable.信号量(以及许多其他类似互斥锁的类型......包括
mutex
)是不可移动的。 You cannot put such a type in a vector
.您不能将此类类型放入
vector
中。 This is not about explicit constructors;这与显式构造函数无关; it's about the lack of a copy or move constructor.
这是关于缺少复制或移动构造函数。
Allocating an array of these is made difficult by the lack of a default constructor.由于缺少默认构造函数,分配这些数组变得困难。 You can try to work around this by wrapping the semaphore in a type that does have a default constructor, for which you would use some default count.
您可以尝试通过将信号量包装在具有默认构造函数的类型中来解决此问题,您将为此使用一些默认计数。
struct default_binary_semaphore
{
std::binary_semaphore sem; //Make it public for easy access to the semaphore
constexpr default_binary_semaphore() : sem (default_value) {}
constexpr explicit default_binary_semaphore(auto count) : sem(count) {}
};
Note that, while you can allocate arrays of this type, the type is still non-moveable.请注意,虽然您可以分配此类型的 arrays,但该类型仍然是不可移动的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.