C++ 11 feature: C++ Multithreading Tutorial: Lock Guard in C++ threading

In this chapter we shall learn about lock guard.

1. lock_guard is a class in C++
2. lock_guard provides RAII style mechanism for acquiring mutex for a scoped block.
3. lock_guard acquires mutex the moment you create an object of lock_guard.
4. When the control leaves the scope, it will automatically unlocks and lock_guard object is destroyed.
5. No need to explicit call unlock function.
6. You cannot copy lock_guard class.

Syntax for creating lock_guard is:

std::lock_guard<std::mutex> lock(m1);

Example of mutex without lock_guard [with simple mutex lock and unlock:]

#include <iostream>
#include <mutex>
#include <thread>

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;


int count = 0;

std::mutex mu;

void incrementCount()
{
    mu.lock();
   		count++;//critial section
   		cout<<count<<endl;
   	mu.unlock();

}

int main(void)
{
    std::thread t1(incrementCount);
    std::thread t2(incrementCount);
    std::thread t3(incrementCount);

    t1.join();
    t2.join();
    t3.join();
    
    
    return 0;
}

Example of mutex with lock_guard:

#include <iostream>
#include <mutex>
#include <thread>

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;


int count = 0;

std::mutex mu;

void incrementCount()
{
    std::lock_guard<std::mutex> lock(mu); //lock_guard lock
   		count++;//critial section
   		cout<<count<<endl;
    // see there is no explicit unlock.
}

int main(void)
{
    std::thread t1(incrementCount);
    std::thread t2(incrementCount);
    std::thread t3(incrementCount);

    t1.join();
    t2.join();
    t3.join();
    
    
    return 0;
}
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *