TheVoidBeing
TheVoidBeing

Reputation: 11

C++ sleep for undetermined amount of time

In my code I want my system to sleep, until a condition has been met. An after having searched i have found #include <unistd.h>, but to me it just looks like it sleeps until the time frame has been met. I was wondering if there was a easy way to make the program wait until the condition has been reached.

Here you have a sample of the code to clarify my point

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

Upvotes: 0

Views: 149

Answers (1)

Superlokkus
Superlokkus

Reputation: 5027

Based on your incomplete pseudo-code and description, here is a class contidion_t, where you can set your condition via set_condition, and a thread blocking in loop will wake up, every time you set it.

#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();
}

Upvotes: 1

Related Questions