2

I need to be able to store "n" number of mutexes at any given time.

These URLs relate directly to my problem storing mutexes in a vector/deque c++ How can I use something like std::vector<std::mutex>?

And I am confident I understand why mutexes can not be stored in containers that might have to move them (as mutexes can't be moved). My question is, have there been any developments in c/c++ since these articles were posted that I might be able to utilize that I don't know about?

A simple array would be nice, but won't work for obvious reasons. A vector or similar would work, except for the fact that the mutexes can't be moved and therefore generates a compiler error. The following does work, but seems to be decried by some. Is there a programmatic reason why the following code example shouldn't be used to solve the problem?

std::vector<std::timed_mutex*> myMutexes;
myMutexes.push_back(new std::timed_mutex());
Weedware
  • 141
  • 1
  • 9
  • 4
    At the absolute very least, using `std::unique_ptr` instead of owning raw pointers would be leaps and bound better. –  Jul 29 '19 at 16:33
  • `std::vector>` is the container for you. basically it works like a `std:list` but it has better cache locality. – NathanOliver Jul 29 '19 at 16:34
  • 1
    Container of `std::mutex` is so strange idea that this must be a [XY problem](http://xyproblem.info/)! You should describe what are you synchronizing since you are doing that wrong for sure? – Marek R Jul 29 '19 at 16:44

1 Answers1

3

From the linked page,

If you need to add non-movable items to the end of a sequence, switch to deque, that will work where vector won't.

If you need insertions or deletions that are neither at the beginning nor at the end, then of course std::deque won't work either and you would need to use something like std::vector<std::unique_ptr<std::mutex>>. This is better than using raw pointers because it guarantees that the mutexes will get released when they're removed from the vector or when the vector goes out of scope (except in the case of abnormal program termination).

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • I am beginning to get the hint that using "new" anything is no longer considered good programming practice these days (showing my age). What is the syntax for adding a mutex to the vector using std::vector>, if you don't mind me asking? – Weedware Jul 29 '19 at 16:45
  • 1
    @Weedware `myMutexes.push_back(std::make_unique());` –  Jul 29 '19 at 16:45
  • 1
    @Weedware `v.push_back(std::make_unique())`. See https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique – Brian Bi Jul 29 '19 at 16:46
  • As usual, you guys rock! Many thanks, I'm off and running again. – Weedware Jul 29 '19 at 16:47