Skip to content

Commit 539e4f5

Browse files
authored
Update main.cpp
1 parent 207b58d commit 539e4f5

File tree

1 file changed

+28
-10
lines changed

1 file changed

+28
-10
lines changed

src/main.cpp

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,47 @@
33
#include <thread>
44
#include <atomic>
55
#include <chrono>
6+
#include <string> // Required for std::stoi
67

7-
int main() {
8-
CacheManager manager(5);
9-
std::atomic<bool> stop_flag(false); // The stop flag
8+
int main(int argc, char* argv[]) {
9+
// --- 1. Read Cache Capacity from Command Line ---
10+
if (argc < 2) {
11+
std::cerr << "Usage: " << argv[0] << " <cache_capacity>" << std::endl;
12+
return 1; // Exit with an error
13+
}
14+
15+
int capacity = 0;
16+
try {
17+
capacity = std::stoi(argv[1]);
18+
} catch (const std::exception& e) {
19+
std::cerr << "Error: Invalid number for cache capacity." << std::endl;
20+
return 1;
21+
}
22+
23+
if (capacity <= 0) {
24+
std::cerr << "Error: Cache capacity must be a positive number." << std::endl;
25+
return 1;
26+
}
27+
28+
std::cout << "Initializing cache with capacity: " << capacity << std::endl;
29+
CacheManager manager(capacity); // Use the capacity from user input
30+
std::atomic<bool> stop_flag(false);
1031

11-
// Pass a reference to the flag to the thread
32+
// --- 2. The Rest of the Program Runs as Before ---
1233
std::thread policySwitcher(&CacheManager::switchPolicy, &manager, std::ref(stop_flag));
1334

14-
// Simulate cache operations
1535
std::cout << "Simulating cache access..." << std::endl;
16-
for (int i = 0; i < 20; i++) {
36+
for (int i = 0; i < (capacity * 4); ++i) { // Simulate based on capacity
1737
manager.accessCache(i, i * 10);
1838
std::this_thread::sleep_for(std::chrono::milliseconds(100));
1939
}
2040

21-
// Let the policy switcher run a few times
2241
std::cout << "Running for 5 seconds before shutdown..." << std::endl;
2342
std::this_thread::sleep_for(std::chrono::seconds(5));
2443

25-
// --- Graceful Shutdown ---
2644
std::cout << "Signaling policy switcher to stop..." << std::endl;
27-
stop_flag.store(true); // Set the flag to true
28-
policySwitcher.join(); // Wait for the thread to finish its loop
45+
stop_flag.store(true);
46+
policySwitcher.join();
2947

3048
std::cout << "Program finished successfully." << std::endl;
3149
return 0;

0 commit comments

Comments
 (0)