Problem description:
So I have been noticing a weird behavior: could be related to std::this_thread::sleep_for(delay);
but I have the following function and every time I run it, it doesn’t seem to take into account the delay no matter how much of I add. I also tried changing the print statement and that doesn’t get reflected either.
void Add(const TimerInfo& timerInfo)
{
std::chrono::seconds delay(20);
/std::this_thread::sleep_for(delay);
TimePoint curTime = Clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(curTime - startTime);
std::cout << "Time elapsed = " << duration.count() << "\n";
}
Expected behavior:
The delay to work or any changes made in the function
Actual behavior:
Described in the first part
Steps to reproduce:
// PQueue.hpp
#pragma once
#include "CallbackTimer.hpp"
#include <queue>
#include <thread>
#include <chrono>
#include <vector>
#include <iostream>
static const TimePoint startTime = Clock::now();
class PQueue
{
public:
void Add(const TimerInfo& timerInfo)
{
// std::cout << "Hola\n";
// std::chrono::seconds delay(20);
// std::this_thread::sleep_for(delay);
TimePoint curTime = Clock::now();
// auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(curTime - startTime);
// std::cout << "Time-elapsed = " << duration.count() << "\n";
}
private:
std::priority_queue<unsigned int, std::vector<unsigned int>, std::greater<unsigned int>> _pQueue;
};
// CallbackTimer.hpp
#pragma once
#include <iostream>
#include <queue>
#include <chrono>
#include <iostream>
#include <functional>
#include <array>
using Clock = std::chrono::steady_clock;
using TimePoint = std::chrono::time_point<Clock>;
using Callback = std::function<void()>;
struct TimerInfo
{
unsigned int expiry;
Callback callback;
unsigned int refTime;
};
std::array<TimerInfo, 2> scheduleA =
{
TimerInfo{1000, []() { std::cout << "A-1\n"; }},
TimerInfo{5000, []() { std::cout << "A-2\n"; }}
};
class CallbackTimer
{
public:
void Add(TimerInfo timerInfo)
{
// unsigned int curTime =
// _pQueue.push(timerInfo);
}
};
// main.cpp
#include <main.h>
#include <util.h>
#include <iostream>
#include "PQueue.hpp"
using namespace std;
int main(void) {
PQueue pqueue;
pqueue.Add(scheduleA[0]);
return 0;
};