📅 2015-Sep-14 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, cpp11, lock, lock_guard, mutex ⬩ 📚 Archive
Launching asynchronous threads is super easy in C++11 as described here. Once you have multi-threading, you might also need locking to handle concurrent access to shared data. Thankfully, locking using mutex is also super easy in C++11!
A std::mutex
object is required to act as the mutex.
The simplest way to lock a section of code is to create a std::lock_guard
object. It takes a mutex as input. This not only creates the lock object but starts the locked section of the code.
At the end of the scope of the std::lock_guard
object, it is unlocked and destroyed. This is thanks due to the RAII design of the lock.
Using these constructs, we can now handle concurrent access to a queue from multiple threads for both adding and removing items from it:
class SharedQueue
{
public:
SharedQueue() {}
void Put(const Foo* item)
{
std::lock_guard<std::mutex> lock(mutex_); // Locking begins
// Code for adding to queue goes here
// Code is unlocked at end of the scope of lock_guard object
}
const Foo* Get()
{
std::lock_guard<std::mutex> lock(mutex_); // Locking begins
// Code for removing from queue goes here
// Code is unlocked at end of the scope of lock_guard object
}
private:
std::mutex mutex_; // Mutex object used for [un]locking this queue
};