I have an std::vector
that is used to pass message to a thread. The vector is protected by a mutex:
vector<int> messages;
std::mutex m;
void postmessage (int msg) {
{
std::unique_lock Lock (m);
messages.push_back (msg);
}
}
When the thread is woken up, it grabs the entire message queue like this:
const auto my_messages = [this] {
std::unique_lock Lock (m);
return move (messages);
} ();
It then processes my_messages
. Questions:
Is this guaranteed to leave the vector in an empty state? In other words, is this an application of constructor (7) on cppreference that guarantees that the vector is left empty?
Are the operations on
messages
guaranteed to be completed before the mutex is unlocked? In other words, is this thread-safe?