mutex

To fix race conditions in multi-threaded environment we need mutex i.e. each thread needs to lock a mutex before modifying or reading the shared data and after modifying the data each thread should unlock the mutex.
In the C++11 threading library, the mutexes are in the <mutex> header file. The class representing a mutex is the std::mutex class.
There are two important methods of mutex:
* lock()
* unlock()
```
#include<iostream>
#include<thread>
#include<vector>
#include<mutex>
using namespace std;

class Wallet {
    int money;
    std::mutex mutex;
public:
    Wallet():money(0){}
    int getMoney()   { return money; }
    void addMoney(int money)
    {
        mutex.lock();
        this->money+=money;
        mutex.unlock();
    }
};

int testMultithreadedWallet() {
    Wallet walletObject;
    vector<thread> threads;
    for(int i = 0; i < 50; ++i){
        threads.push_back(thread(&Wallet::addMoney, &walletObject, 1000));
    }
    for(int i = 0; i < threads.size() ; i++) {
        threads.at(i).join();
    }
    return walletObject.getMoney();
}
int main()
{
    int val = 0; 
    for(int k = 0; k < 1000; k++) {
        if((val = testMultithreadedWallet()) != 50000) {
            cout << "Error at count = "<<k
                <<"  Money in Wallet = "<<val << endl;
        }
    }
    return 0;
}
```
std::lock_guard is a class template, which implements the RAII for mutex. It wraps the mutex inside it’s object and locks the attached mutex in its constructor. When it’s destructor is called it releases the mutex.
```
#include<iostream>
#include<thread>
#include<vector>
#include<mutex>
using namespace std;

class Wallet
{
    int money;
    std::mutex mutex;
public:
    Wallet() :money(0){}
    int getMoney()   { return money; }
    void addMoney(int money) {
        lock_guard<std::mutex> lockGuard(mutex);
        this->money+=money;
    }
 };
 
int testMultithreadedWallet() {
    Wallet walletObject;
    vector<thread> threads;
    for(int i = 0; i < 50; ++i){
        threads.push_back(thread(&Wallet::addMoney, &walletObject, 1000));
    }
    for(int i = 0; i < threads.size() ; i++) {
        threads.at(i).join();
    }
    return walletObject.getMoney();
}
int main()
{
    int val = 0; 
    for(int k = 0; k < 1000; k++) {
        if((val = testMultithreadedWallet()) != 50000) {
            cout << "Error at count = "<<k
                <<"  Money in Wallet = "<<val << endl;
        }
    }
    return 0;
}
```