gpt4 book ai didi

c++ - 延迟执行代码

转载 作者:太空宇宙 更新时间:2023-11-04 13:13:05 24 4
gpt4 key购买 nike

假设我们在一个函数中,只要按下鼠标按钮就会被调用

static inline LRESULT CALLBACK WndProc(const int code, const WPARAM wParam, const LPARAM lParam){


}

我现在想在 5 秒内没有按下任何按钮后执行一些代码。如果 2 秒后,用户单击鼠标按钮,“计时器”应重置并再等待 5 秒。

这甚至可以用 C++ 完成吗?如果我使用 Sleep(5000),如果中间按下另一个按钮,我无法阻止代码运行。

最佳答案

这是我的类(它并不完美,但你可以看看它是如何完成的)来控制套接字后面的程序的心跳。当调用 beat() 方法时,计时器被“重置”。

    class HeartbeatController
{
private:
using ms = std::chrono::milliseconds;
public:
HeartbeatController(std::function<void()> &heartbeatLostCallback,
const ms &panicTime = ms{5000}, //time in milliseconds, after which panic code will be executed
const ms &checkDuration = ms{ 1000 }) noexcept :
heartbeatLostCallback{ heartbeatLostCallback }
{}

~HeartbeatController() = default;

HeartbeatController(HeartbeatController &&other) :
heartbeatLostCallback{ std::move(other.heartbeatLostCallback) },
loopThread{ std::move(other.loopThread) },
lastBeat{ std::move(other.lastBeat) },
panicTime{ std::move(other.panicTime) },
checkDuration{ std::move(other.checkDuration) }
{}

HeartbeatController& operator=(HeartbeatController &&other)
{
heartbeatLostCallback = std::move(other.heartbeatLostCallback);
loopThread = std::move(other.loopThread);
lastBeat = std::move(other.lastBeat);
panicTime = std::move(other.panicTime);
checkDuration = std::move(other.checkDuration);

return *this;
}

HeartbeatController(const HeartbeatController&) = delete;
HeartbeatController& operator=(const HeartbeatController&) = delete;

void interrupt() noexcept
{
interrupted = true;
}

void beat() noexcept
{
lastBeat = Clock::now();
}

void start()
{
auto loop = [this]
{
while (!interrupted)
{
if (Clock::now() - lastBeat > panicTime)
heartbeatLostCallback(); //here you can insert some your code which you wanna execute after no beat() for panicTime duration

std::this_thread::sleep_for(checkDuration);
}
};

lastBeat = Clock::now();

loopThread = std::thread{ loop };
}

private:
using Clock = std::chrono::system_clock;

std::reference_wrapper<std::function<void()>> heartbeatLostCallback;
std::thread loopThread;

std::chrono::time_point<Clock> lastBeat;
std::chrono::milliseconds panicTime;
std::chrono::milliseconds checkDuration;

bool interrupted = false;
};

关于c++ - 延迟执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38787898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com