#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
std::mutex mtx;
int shared_resource = 0;
void worker(int id) {
std::unique_lock<std::mutex> lock(mtx, std::defer_lock);
// Simulate some work before locking
std::this_thread::sleep_for(std::chrono::milliseconds(id * 100));
lock.lock();
shared_resource += id;
std::cout << "Thread " << id << " added " << id << ". New value: " << shared_resource << std::endl;
lock.unlock();
// Simulate more work after unlocking
std::this_thread::sleep_for(std::chrono::milliseconds(100));
lock.lock();
shared_resource *= 2;
std::cout << "Thread " << id << " doubled. New value: " << shared_resource << std::endl;
}
int main() {
std::vector<std::thread> threads;
for (int i = 1; i <= 5; ++i) {
threads.emplace_back(worker, i);
}
for (auto& t : threads) {
t.join();
}
return 0;
}