c++ - How can I use something like std::vector<std::mutex>? -
i have large, potentially varying, number of objects concurrently written into. want protect access mutexes. end, thought use std::vector<std::mutex>
, doesn't work, since std::mutex
has no copy or move constructor, while std::vector::resize()
requires that.
what recommended solution conundrum?
edit: c++ random-access containers require copy or move constructors re-sizing? std::deque help?
edit again
first, thoughts. i'm not interested in solutions avoid mutices and/or move them objects (i refrain giving details/reasons). given problem want adjustable number of mutices (where adjustment guaranteed occur when no mutex locked), there appear several solutions.
1 use fixed number of mutices , use hash-function map objects mutices (as in captain oblivous's answer). result in collisions, number of collisions should small if number of mutices larger number of threads, still smaller number of objects.
2 define wrapper class (as in comicsansms's answer), e.g.
struct mutex_wrapper : std::mutex { mutex_wrapper() = default; mutex_wrapper(mutex_wrapper const&) noexcept : std::mutex() {} bool operator==(mutex_wrapper const&other) noexcept { return this==&other; } };
and use std::vector<mutex_wrapper>
.
3 use std::unique_ptr<std::mutex>
manage individual mutexes (as in matthias's answer). problem approach each mutex individually allocated , de-allocated on heap. therefore, prefer
4 std::unique_ptr<std::mutex[]> mutices( new std::mutex[n_mutex] );
when number n_mutex
of mutices allocated initially. should number later found insufficient, simply
if(need_mutex > n_mutex) { mutices.reset( new std::mutex[need_mutex] ); n_mutex = need_mutex; }
so of these (1,2,4) should use?
vector
requires values movable, in order maintain contiguous array of values grows. create vector containing mutexes, couldn't might need resize it.
other containers don't have requirement; either deque
or [forward_]list
should work, long construct mutexes in place either during construction, or using emplace()
or resize()
. functions such insert()
, push_back()
not work.
alternatively, add level of indirection , store unique_ptr
; comment in answer indicates believe cost of dynamic allocation unacceptable.
Comments
Post a Comment