从轮询切换到基于事件的系统

Switching from polling to event based system

本文关键字:事件 系统 于事件      更新时间:2023-10-16

>基本上我想要实现的是检查自上次检查以来数据是否已更改。

我在这里做的是启动一个单独的线程,该线程在循环中连续运行并在循环结束时检查停止变量。stop 变量是一个全局变量,所以我可以轻松地给它一个 0 值来终止主线程的轮询循环。

在循环中,我有一组变量,用于保存我在上一次迭代中检索到的数据的值,以及一组用于存储最近检索的数据的变量。我所做的只是将变量与新数据与保存先前数据的变量进行比较。在此之后,我将保存先前数据的变量集更新为最新数据。

我想问一下是否有更有效的方法? 也许不需要轮询的东西?

是的;一种方法是让轮询线程等待条件变量,并让生产者通过发出相同条件变量的信号来唤醒它。

在 cpp首选项中给出了C++ 中的一个例子:

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
void worker_thread()
{
    // Wait until main() sends data
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk, []{return ready;});
    // after the wait, we own the lock.
    std::cout << "Worker thread is processing datan";
    data += " after processing";
    // Send data back to main()
    processed = true;
    std::cout << "Worker thread signals data processing completedn";
    // Manual unlocking is done before notifying, to avoid waking up
    // the waiting thread only to block again (see notify_one for details)
    lk.unlock();
    cv.notify_one();
}
int main()
{
    std::thread worker(worker_thread);
    data = "Example data";
    // send data to the worker thread
    {
        std::lock_guard<std::mutex> lk(m);
        ready = true;
        std::cout << "main() signals data ready for processingn";
    }
    cv.notify_one();
    // wait for the worker
    {
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return processed;});
    }
    std::cout << "Back in main(), data = " << data << 'n';
    worker.join();
}