gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:11:11 26 4
gpt4 key购买 nike

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

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

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

我想问问有没有更有效的方法呢?也许不需要轮询的东西?

最佳答案

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

cppreference 中给出了一个 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 data\n";
data += " after processing";

// Send data back to main()
processed = true;
std::cout << "Worker thread signals data processing completed\n";

// 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 processing\n";
}
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++ - 从轮询切换到基于事件的系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35631676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com