![]() |
In multi-threaded programming, it is essential to ensure that shared resources are accessed in a controlled and synchronized manner to maintain data consistency and prevent race conditions. The std::mutex synchronization primitive was introduced in C++ 11 to allow threads to acquire exclusive ownership of a shared resource for a period of time, ensuring thread-safe access. In this article, we will learn how to use the std::mutex synchronization primitive in C++. std::mutex Synchronization Primitive in C++Before using the std::mutex synchronization primitive, we must understand how it works. A std::mutex (short for mutual exclusion) is a lock object that allows only one thread to access a shared resource at a time. When a thread needs to access a shared resource, it attempts to acquire the mutex lock. If the lock is available, then the thread acquires it and proceeds to access the shared resource. If the lock is currently held by another thread, the requesting thread will be blocked until the lock is released. Following is the syntax to use the std::mutex in C++: SyntaxTo understand the syntax of std::mutex in C++, we must know how to declare the mutex object, how to acquire a lock on mutex, and how to unlock it. Declaring the mutex object std::mutex mtx_name; where:
Locking the mutex mtx_name.lock() The lock() function is used to acquire the lock on the mutex object. If the mutex is already locked by another thread, then the calling thread is blocked until the mutex is free. Unlocking the mutex mtx_name.unlock() The unlock() function releases the lock on the mutex object. It is essential to unlock the mutex when the thread has completed it’s job so that the shared resource can be made available for the other threads as well. C++ Program to use std::mutex Synchronization PrimitiveThe following program illustrates how std::mutex synchronization primitive can be used in C++:
Final value of shared_data: 2000000 Time Complexity: O(N), where N is the number of iterations. ExplanationIn the above example , we have two threads that called the increment_data function concurrently, which increments the shared_data variable one million times. The std::mutex object mtx ensures that only one thread can access the shared_data variable at a time and also ensures no race condition occurs during the execution of the program. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 18 |