#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
int totalItems = 0;
std::mutex inventoryMutex; // Global mutex for synchronization
void processShipment() {
for (int i = 0; i < 10000; ++i) {
// Critical section start
std::lock_guard<std::mutex> guard(inventoryMutex);
totalItems++;
// Critical section end (guard is destroyed, mutex unlocked)
}
}
int main() {
{
// Launch two threads attempting to modify the same variable
std::jthread robot1(processShipment);
std::jthread robot2(processShipment);
} // Both threads automatically join here
std::cout << "Final Inventory Count: " << totalItems << "\n";
if (totalItems == 20000) {
std::cout << "Success! Count is correct.\n";
} else {
std::cout << "Error! Race condition detected.\n";
}
return 0;
}