gpt4 book ai didi

C++ sleep 时间不确定

转载 作者:行者123 更新时间:2023-11-28 04:02:32 25 4
gpt4 key购买 nike

在我的代码中,我希望我的系统休眠,直到满足条件。搜索后我找到了 #include <unistd.h> ,但对我来说,它看起来就像是在满足时间范围之前一直在 sleep 。我想知道是否有一种简单的方法可以让程序等待直到达到条件。

这里有一个代码示例来阐明我的观点

bool check() {
while (condition) {
sleep.here();
} else {
run.the.rest();
}
}

最佳答案

根据您不完整的伪代码和描述,这里有一个类contidion_t,您可以在其中通过set_condition 设置您的条件,并在 中阻塞一个线程loop 将在您每次设置时唤醒。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>

struct condition_t {
public:
template <typename T>
void loop(T the_rest) {
while(running) {
std::unique_lock<std::mutex> lock_guard(m);
cv.wait(lock_guard, [this] { return ready.load(); });
the_rest();
ready = false;
}
}

void set_condition(bool value) {
ready = value;
if (value) {
cv.notify_one();
}
}

void stop_running() {
running = false;
ready = true;
cv.notify_all();
}
~condition_t () {stop_running();}

private:
std::mutex m;
std::condition_variable cv;
std::atomic<bool> ready{false};
std::atomic<bool> running{true};
};

int main() {
condition_t condition;
std::thread thread(&condition_t::loop<void (void)>, &condition, [] () {
std::cout << "Doing the rest" << std::endl;
});
std::cout << "Thread created but waits\nInput something for continue:";
int something;
std::cin >> something;
std::cout << "Continueing\n";
condition.set_condition(true);
std::cout << "Input something to stop running:";
std::cin >> something;
condition.stop_running();

thread.join();
}

关于C++ sleep 时间不确定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59266305/

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