mutex in the thread explained in simple examples in detail

mutex in the thread explained in simple examples in detail

A mutex is a locked object that acts as a notification when critical code parts demand exclusive access. It prohibits other threads with the same protection from accessing the same memory areas at the same time.

Points to remember:

  1. Never return a pointer or reference of data being protected.
  2. Passing code to the protected data for which you don’t have control.
  3. Std::mutex cannot be moved or copied.
  4. Mutex objects offer exclusive ownership but forbid recursivity; A thread cannot lock a mutex that it already has;
  5. std::mutex is rarely used directly: Since C++17, you can use std::unique lock, std::lock guard, or std::scoped lock. Locking should be managed in a more exception-safe manner.

Member functions


(constructor) Construct mutex (public member function
lock Lock mutex (public member function)
try_lock Lock mutex if not locked (public member function)
unlock Unlock mutex (public member function)
native_handle Get native handle (public member function)

Native handle

native_handle returns the underlying implementation-defined native handle object

Example

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

std::list<int> my_list;
std::mutex m;


/// <summary>
/// mutex ensures that the only one thread at a time get an access to lush element into list and other requests are queued to wit state.
/// Note : 
///         1. Never return pointer or reference of data being protected.
///         2. Passing code to the protected data for which you don't have control.
/// </summary>
void push_to_list(int const& x)
{
	std::lock_guard<std::mutex> lg(m);
	my_list.push_back(x);
}


int  main()
{
	std::thread thread_1(push_to_list, 4);
	std::thread thread_2(push_to_list, 11);

	thread_1.join();
	thread_2.join();
}