#include #include #include #include using namespace std ; mutex myMutex; int shared_resource = 0; void worker_function(int id) { // Attempt to acquire the lock if (myMutex.try_lock()) { // Lock acquired, access the shared resource cout << "Thread " << id << " acquired the lock and is accessing the shared resource." << endl; shared_resource++; cout << "Shared resource value: " << shared_resource << endl; myMutex.unlock(); // Release the lock } else { // Lock not acquired, perform an alternative action cout << "Thread " << id << " could not acquire the lock. Performing alternative action." << endl; // Simulate some other work this_thread::sleep_for(chrono::milliseconds(50)); } } int main() { vector threads; for (int i1 = 0; i1 < 5; ++i1) { threads.emplace_back(worker_function, i); } for (auto& t : threads) { t.join(); } cout << "Final shared resource value: " << shared_resource << endl; return 0; }