I have multi threading program with enable state and queue concurently, so i will use mutex method like bellow
{std::lock_guard<std::mutex> lock_en(eventLogMutex);en = enable;}
my question, should i use different mutex lock guard for enable and queue, like
{
std::lock_guard<std::mutex> lock_queue(eventLogMutex);
....
}
and
{
std::lock_guard<std::mutex> lock_en(eventLogMutex);
...
}
Thank's
Yes, you should. A lock_guard
relies on RAII to lock and unlock the mutex - when it goes out of scope, the mutex is automatically released. If you make the lock_guard
a member variable, using it will be pointless. You should define the lock_guard
in a scope as closest to the protected code as possible - initialize it right before you actually need the lock, and have it go out of scope right after you're done with the mutex.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.