I have the following array of mutexes:
std::mutex mtx[5];
And I would like to lock them all with an RAII style:
std::lock_guard<std::mutex> grd[5] { mtx[0], mtx[1], mtx[2], mtx[3], mtx[4] };
While the above code works, it isn't ideal as I can't write it independently of the size of the array (here 5).
Is there a way to do that? Shall I work with template magic to create an std::initializer_list out of an array? (is that possible?)
I'm open to using std::array or std::vector instead of C-style arrays, I used those here for conciseness. Ideally this works in C++14 but any solution up to latest standards is fine.
std::lock_guard<std::mutex> grd[5] { mtx[0], mtx[1], mtx[2], mtx[3], mtx[4] };to compile in g++, clang++ or MSVC. - Ted Lyngmo