从轮询切换到基于事件的系统
Switching from polling to event based system
>基本上我想要实现的是检查自上次检查以来数据是否已更改。
我在这里做的是启动一个单独的线程,该线程在循环中连续运行并在循环结束时检查停止变量。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();
}
相关文章:
- C++事件系统 - 多态事件和事件处理程序
- 事件系统:使用类型转换或联合进行继承
- 将函数名称传递给事件总线系统中的事件类
- SDL 2,如何使用事件系统和异步绘制
- 事件记录API未写入系统日志
- Qt中一个类似事件系统的信号/槽,没有分叉-C++
- 在C Linux中捕获系统事件
- C++事件系统-使用基于堆或堆栈的事件
- OSX-Qt应用程序在接收系统事件QEvent::FileOpen时崩溃
- 多线程事件系统
- 订阅windows系统事件本机c++
- 具有从 c++ 中的非模板基类派生的模板类的事件系统
- NodeJS 文件系统 监视抛出事件两次或更多次
- 从轮询切换到基于事件的系统
- 事件系统优化
- C++中的简单事件系统
- C++:游戏引擎的事件系统实现
- 事件系统类似于c# (. net ?)
- 用于c++的事件系统
- 类内部的Std::bind,事件系统的一般概念