You are on page 1of 2

### What is mutex | Stream Synchronization

#multithreading
[[(thread)]] [[1.th.parameters]] [[2.th.&return]] [[3.th.lambda]] [[4.th.methods]]
[[5.mutex]] [[6.mutex.lock_guard]] [[7.Deadlock]] [[8.recursive_mutex]] [[9.
unique_lock]]

---
In multi-threaded applications, where multiple threads access and manipulate shared
resources concurrently, race conditions can occur. Race conditions happen when
multiple threads try to access and manipulate a shared resource simultaneously,
leading to unpredictable behavior and bugs in the program.

To prevent race conditions, synchronization mechanisms such as mutexes are used.


Mutexes (short for "mutual exclusion") are objects that ensure that only one thread
at a time can access a shared resource. When a thread acquires a mutex, it enters
into a critical section, a portion of code that must be executed exclusively by
that thread.

In C++, the `std::mutex` class is provided as a synchronization mechanism. A mutex


is an object of the `std::mutex` class that can be locked and unlocked by threads.
A locked mutex is not accessible by other threads until it is unlocked by the
thread that holds the lock.

Here is an example of using a `std::mutex` to synchronize access to a shared


resource:
```cpp
#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx; // declare a mutex

void shared_resource()
{
mtx.lock(); // acquire the lock
// do some work on the shared resource
std::cout << "Thread " << std::this_thread::get_id() << " is accessing the
shared resource\n";
mtx.unlock(); // release the lock
}

int main()
{
std::thread t1(shared_resource);
std::thread t2(shared_resource);

t1.join();
t2.join();

return 0;
}
```

In this example, the `shared_resource()` function is accessed by two threads `t1`


and `t2`. Before accessing the shared resource, the threads acquire the lock using
the `mtx.lock()` function. The `std::mutex::lock()` function blocks the thread if
the mutex is already locked by another thread. Once the lock is acquired, the
thread can access the shared resource. After accessing the shared resource, the
thread releases the lock using the `mtx.unlock()` function.
It's important to note that using a mutex comes with a performance cost, as
acquiring and releasing the lock requires overhead. It's also crucial to avoid
deadlocks, which occur when two or more threads are waiting for each other to
release a lock, causing the program to hang indefinitely. To avoid deadlocks, it's
important to use a consistent locking order and to keep the critical section as
short as possible.

In summary, mutexes are a powerful synchronization mechanism that can be used to


prevent race conditions in multi-threaded applications. The `std::mutex` class in
C++ provides a simple way to use mutexes in your programs.

# My Example

```cpp
#include <iostream>
#include <mutex>
#include <thread>
#include "SimpleTimer.h"

using namespace std;

mutex mtx;

void Print(char ch) {

this_thread::sleep_for(chrono::milliseconds(2000)); // Long Code Emulator

mtx.lock();
for (int i = 0; i < 5; ++i){
for (int i = 0; i < 10; i++) {
cout << ch;
this_thread::sleep_for(chrono::milliseconds(20));
}
cout << endl;
}
cout << endl;
mtx.unlock();

this_thread::sleep_for(chrono::milliseconds(2000)); // Long Code Emulator


}

int main() {

SimpleTimer timer;

thread t1(Print, '*');


thread t2(Print, '#');

t1.join();
t2.join();

return 0;
}
```

You might also like