📜  如何在睡眠时唤醒std :: thread?

📅  最后修改于: 2021-08-24 16:41:37             🧑  作者: Mango

在本文中,我们将讨论如何在std :: thread休眠时唤醒它。众所周知,线程在睡眠时无法退出。因此,使用以下命令将其唤醒:

下面是实现相同代码的伪代码:

C++
// Custom Class
struct MyClass {
  
    // Constructor
    MyClass()
        : my_thread([this]() {
            this->thread();
        })
    {
    }
  
    // Destructor
    ~MyClass()
    {
        {
            std::lock_guard l(m_);
            stop_ = true;
        }
        c_.notify_one();
        my_thread.join();
    }
  
    // Function that implements the
    // thread
    void thread()
    {
        while (this->wait_for(std::chrono::minutes(2)))
            SendStatusInfo(some_info);
    }
  
    // Function to returns false when
    // the thread is stopped
    template 
    bool wait_for(Duration duration)
    {
        std::unique_lock l(m_);
        return !c_.wait_for(l, duration, [this]() {
            return stop_;
        });
    }
  
    // Conditions Variable
    std::condition_variable c_;
    std::mutex m_;
    bool stop_ = false;
    std::thread my_thread;
};


C++
// Promise Condition
std::promise pr;
  
// Start the thread
std::thread thr{
        [fut = pr.get_future()]{
  
            // Iterate until the condition
            // break
            while (true){
                if (fut.wait_for(std::chrono::minutes(2))
                    != std::future_status::timeout) return;
}
}
}
;
  
// When ready to stop
pr.set_value();
  
// Join the thread
thr.join();


C++
// C++ program to illustrate the waking
// of the thread while it is sleeping
#include 
using namespace std;
  
std::deque q;
std::mutex mu;
std::condition_variable cond;
  
// Function to create the thread 1
void function_1()
{
    // Initialize a counter variable
    int count = 10;
  
    // Iterate until count is positive
    while (count > 0) {
  
        // Mutex
        std::unique_lock locker(mu);
  
        // Push the current count in
        // the dequeue
        q.push_front(count);
        locker.unlock();
        cond.notify_one();
  
        // If there is any waiting thread
        // then notify that thread
        std::this_thread::sleep_for(
            chrono::seconds(1));
  
        // Decrement the count
        count--;
    }
}
  
// Function to create the thread 2
void function_2()
{
    // Initialize a variable to get
    // the data from the deque
    int data = 0;
  
    while (data != 1) {
  
        std::unique_lock locker(mu);
  
        cond.wait(locker, []() {
            return !q.empty();
        });
  
        // False Waking of thread
        data = q.back();
        q.pop_back();
        locker.unlock();
  
        // Print the message
        cout << "t2 got a value from"
                " t1"
             << data << '\n';
    }
}
  
// Driver Code
int main()
{
    // Create thread 1
    std::thread t1(function_1);
  
    // Create thread 2
    std::thread t2(function_2);
  
    // Join the threads
    t1.join();
    t2.join();
  
    return 0;
}


下面是另一个示例来说明这一点:

上面的命令可以用作前一种方法的简单替代方法。在这种情况下, Future不会受到错误唤醒的影响,并且不需要互斥体进行同步。下面是实现相同代码的伪代码:

C++

// Promise Condition
std::promise pr;
  
// Start the thread
std::thread thr{
        [fut = pr.get_future()]{
  
            // Iterate until the condition
            // break
            while (true){
                if (fut.wait_for(std::chrono::minutes(2))
                    != std::future_status::timeout) return;
}
}
}
;
  
// When ready to stop
pr.set_value();
  
// Join the thread
thr.join();

下面是说明上述概念的程序:

C++

// C++ program to illustrate the waking
// of the thread while it is sleeping
#include 
using namespace std;
  
std::deque q;
std::mutex mu;
std::condition_variable cond;
  
// Function to create the thread 1
void function_1()
{
    // Initialize a counter variable
    int count = 10;
  
    // Iterate until count is positive
    while (count > 0) {
  
        // Mutex
        std::unique_lock locker(mu);
  
        // Push the current count in
        // the dequeue
        q.push_front(count);
        locker.unlock();
        cond.notify_one();
  
        // If there is any waiting thread
        // then notify that thread
        std::this_thread::sleep_for(
            chrono::seconds(1));
  
        // Decrement the count
        count--;
    }
}
  
// Function to create the thread 2
void function_2()
{
    // Initialize a variable to get
    // the data from the deque
    int data = 0;
  
    while (data != 1) {
  
        std::unique_lock locker(mu);
  
        cond.wait(locker, []() {
            return !q.empty();
        });
  
        // False Waking of thread
        data = q.back();
        q.pop_back();
        locker.unlock();
  
        // Print the message
        cout << "t2 got a value from"
                " t1"
             << data << '\n';
    }
}
  
// Driver Code
int main()
{
    // Create thread 1
    std::thread t1(function_1);
  
    // Create thread 2
    std::thread t2(function_2);
  
    // Join the threads
    t1.join();
    t2.join();
  
    return 0;
}

输出:

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”