|
3 | 3 | #include <thread> |
4 | 4 | #include <atomic> |
5 | 5 | #include <chrono> |
| 6 | +#include <string> // Required for std::stoi |
6 | 7 |
|
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); |
10 | 31 |
|
11 | | - // Pass a reference to the flag to the thread |
| 32 | + // --- 2. The Rest of the Program Runs as Before --- |
12 | 33 | std::thread policySwitcher(&CacheManager::switchPolicy, &manager, std::ref(stop_flag)); |
13 | 34 |
|
14 | | - // Simulate cache operations |
15 | 35 | 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 |
17 | 37 | manager.accessCache(i, i * 10); |
18 | 38 | std::this_thread::sleep_for(std::chrono::milliseconds(100)); |
19 | 39 | } |
20 | 40 |
|
21 | | - // Let the policy switcher run a few times |
22 | 41 | std::cout << "Running for 5 seconds before shutdown..." << std::endl; |
23 | 42 | std::this_thread::sleep_for(std::chrono::seconds(5)); |
24 | 43 |
|
25 | | - // --- Graceful Shutdown --- |
26 | 44 | 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(); |
29 | 47 |
|
30 | 48 | std::cout << "Program finished successfully." << std::endl; |
31 | 49 | return 0; |
|
0 commit comments