#includestd::mutex mtx; // create mutex object // ... mtx.lock(); // acquire ownership of the mutex object // critical section... mtx.unlock(); // release ownership of the mutex object
#includeThis example shows how `std::mutex::unlock()` can be used with multiple threads accessing a shared resource. The `push_back()` function adds an element to the vector while holding ownership of the mutex object. This ensures that only one thread can modify the vector at a time. The `join()` function is called to wait for the threads to finish executing. Finally, the vector elements are printed to the console. The `std::mutex` class is part of the C++ Standard Library (header file: `#include #include #include std::mutex mtx; // create mutex object std::vector vec; void push_back(int num) { mtx.lock(); // acquire ownership of the mutex object vec.push_back(num); mtx.unlock(); // release ownership of the mutex object } int main() { // ... std::thread t1(push_back, 1); std::thread t2(push_back, 2); t1.join(); t2.join(); // print vector elements for (int i = 0; i < vec.size(); i++) { std::cout << vec[i] << std::endl; } // ... return 0; }