#include #include #include #include // For chrono::milliseconds using namespace std ; mutex myMutex; int shared_data = 0; void worker_function(int id) { for (int i1 = 1; i1 <= 5; ++i1) { // Attempt to acquire the lock if (myMutex.try_lock()) { // Lock acquired, perform critical section operations shared_data++; cout << "Thread " << id << " acquired lock, shared_data: " << shared_data << endl; myMutex.unlock(); // Release the lock } else { // Lock not acquired, perform alternative action or retry later cout << "Thread " << id << " could not acquire lock, doing something else..." << endl; // Simulate doing something else for a short period before retrying i1-- ; this_thread::sleep_for(chrono::milliseconds(50)); } this_thread::sleep_for(chrono::milliseconds(100)); // Simulate some work } } int main() { thread t1(worker_function, 1); thread t2(worker_function, 2); thread t3(worker_function, 3); t1.join(); t2.join(); t3.join(); cout << "Final shared_data: " << shared_data << endl; return 0; }