I need to protect data container with std::mutex that is used in for loop like this:
for (auto it = data.begin(); it != data.end(); ++it)
{
std::cout << it->param;
...
}
I can think of several options but they are ugly like this:
{ // artificial scope
std::scoped_lock lock(myMutex)
for (auto it = data.begin(); it != data.end(); ++it)
{
std::cout << it->param;
...
}
}
Is there a nice-looking method to achieve this? I am thinking about something like the following (C++17), but this does not compile. :(
for (std::scoped_lock lock(myMutex), auto it = data.begin(); it != data.end(); ++it)
Or,
for (auto [lock, it] = std::pair(std::scoped_lock lock(myMutex), data.begin()); it != data.end(); ++it)