PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 30, 2022

[FIXED] How to declare and initialize a vector of semaphores in c++?

 September 30, 2022     c++, c++20, concurrency, constructor     No comments   

Issue

Say I have n different resources. Let's say n = 5 as an example, but n can be large and optionally an input value. I want to initialize a vector of n binary semaphores. How do I do that?

I believe the problem is because the constructor for binary_semaphore or counting_semaphore has been marked 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. Is there a way to solve this problem?


Solution

Semaphores (along with many other mutex-like types... including mutex) are non-moveable. You cannot put such a type in a 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.



Answered By - Nicol Bolas
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing