Practical Sleep Examples
Real-World Sleep Scenarios
Sleep methods are essential in various programming scenarios, demonstrating practical applications across different domains.
1. Periodic Task Execution
#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
void periodicTask() {
std::vector<int> data = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; ++i) {
std::cout << "Processing data: " << data[i] << std::endl;
// Sleep between iterations
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
periodicTask();
return 0;
}
2. Network Request Retry Mechanism
#include <iostream>
#include <thread>
#include <chrono>
bool sendNetworkRequest() {
int maxRetries = 3;
for (int attempt = 1; attempt <= maxRetries; ++attempt) {
try {
// Simulated network request
std::cout << "Attempt " << attempt << " to send request" << std::endl;
// Exponential backoff strategy
std::this_thread::sleep_for(std::chrono::seconds(attempt * 2));
} catch (...) {
if (attempt == maxRetries) {
std::cout << "Request failed after " << maxRetries << " attempts" << std::endl;
return false;
}
}
}
return true;
}
Sleep Strategy Comparison
Scenario |
Sleep Method |
Duration |
Purpose |
Polling |
sleep_for |
Short intervals |
Check resource availability |
Retry Mechanism |
sleep_for |
Exponential backoff |
Network resilience |
Animation |
sleep_for |
Frame delay |
Controlled animation |
3. Simulated Progress Indicator
#include <iostream>
#include <thread>
#include <chrono>
void simulateProgress() {
for (int progress = 0; progress <= 100; progress += 10) {
std::cout << "Progress: " << progress << "%" << std::endl;
// Simulate work with sleep
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
int main() {
simulateProgress();
return 0;
}
Sleep Method Workflow
graph TD
A[Start Task] --> B[Perform Operation]
B --> C{Need Delay?}
C --> |Yes| D[Apply Sleep]
D --> E[Continue Execution]
C --> |No| E
- Use sleep judiciously
- Prefer high-precision methods from
<chrono>
- Consider alternative synchronization techniques
- LabEx recommends minimal sleep duration for optimal performance
Advanced Sleep Techniques
- Conditional sleeping
- Dynamic sleep intervals
- Cancellable sleep operations
- Cross-platform sleep implementations
By mastering these practical sleep examples, developers can create more robust and responsive applications with controlled timing and execution flow.