How to lock using mutex in C++

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s