Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to lock using mutex in C++

📅 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!

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
};

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧