C++ 睡眠时间不确定
C++ sleep for undetermined amount of time
在我的代码中,我希望我的系统休眠,直到满足条件。搜索后,我找到了 #include <unistd.h>
,但对我来说,它看起来就像是在满足时间范围之前一直在睡觉。我想知道是否有一种简单的方法可以让程序等待直到达到条件。
这里有一个代码示例来阐明我的观点
bool check() {
while (condition) {
sleep.here();
} else {
run.the.rest();
}
}
根据你不完整的伪代码和描述,这里有一个 class contidion_t
,你可以通过 set_condition
设置你的条件,[=13] 中有一个线程阻塞=] 每次设置都会唤醒。
#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();
}
在我的代码中,我希望我的系统休眠,直到满足条件。搜索后,我找到了 #include <unistd.h>
,但对我来说,它看起来就像是在满足时间范围之前一直在睡觉。我想知道是否有一种简单的方法可以让程序等待直到达到条件。
这里有一个代码示例来阐明我的观点
bool check() {
while (condition) {
sleep.here();
} else {
run.the.rest();
}
}
根据你不完整的伪代码和描述,这里有一个 class contidion_t
,你可以通过 set_condition
设置你的条件,[=13] 中有一个线程阻塞=] 每次设置都会唤醒。
#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();
}