I am very confused about the difference between a lock and mutex. In Boost docs, it says,
Lock Types
Mutex Types
In another article, I see functions like this,
boost::shared_mutex _access; void reader() { boost::shared_lock< boost::shared_mutex > lock(_access); // do work here, without anyone having exclusive access } void conditional_writer() { boost::upgrade_lock< boost::shared_mutex > lock(_access); // do work here, without anyone having exclusive access if (something) { boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock); // do work here, but now you have exclusive access } // do more work here, without anyone having exclusive access }
Updated questions
A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes. A mutex is the same as a lock but it can be system wide (shared by multiple processes).
The mutual exclusion (mutex) locks or the mutex is the simplest solution. We use the mutex locks to protect the critical section and prevent the race conditions. A process needs to acquire the lock before it accesses its critical section, and it releases the lock once it finishes the execution of the critical section.
A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore.
Mutex: Use a mutex when you (thread) want to execute code that should not be executed by any other thread at the same time.
A mutex is a synchronization object. You acquire a lock on a mutex at the beginning of a section of code, and release it at the end, in order to ensure that no other thread is accessing the same data at the same time. A mutex typically has a lifetime equal to that of the data it is protecting, and that one mutex is accessed by multiple threads.
A lock object is an object that encapsulates that lock. When the object is constructed it acquires the lock on the mutex. When it is destructed the lock is released. You typically create a new lock object for every access to the shared data.
A mutex is an object which can be locked. A lock is the object which maintains the lock. To create a lock, you need to pass it a mutex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With