如何等待一个变量为真之前继续在c++ MFC?



我有一个MFC GUI线程发送/读取消息到/从硬件和另一个MFC工作线程发送一些命令来控制硬件。在我继续发送下一个命令之前,我如何等待变量为真?当从硬件接收到确认消息时,该变量被设置为true。

bool PortRead = false;
void onEventRead() // portread will be set to true from gui thread using callback to main thread
{
PortRead = true; 
}
void sendCommands()
{
send (message1); 
wait for Portread == true;
portread = false; 
send (message2); 
wait for Portread == true;
portread = false; 
}

您可以通过轮询或中断(或回调)来实现这一点。如果您想轮询(也称为忙等待),像这样的内容就足够了:

// Send signal to hardware
while (!variable) {} // Waits here until variable is true
// Proceed with program

中断有点棘手,特别是因为您没有提供关于如何与该硬件接口的模式细节,或者它是否具有某种类型的API或库。如果你可以控制其他线程,你可以使用std::condition_variable::wait,甚至使用Qt和回调的信号/插槽方案。

但是,根据您的代码,这可能有效:
std::condition_variable cv;
std::mutex cv_m;
void onEventRead()
{
cv.notify_all();
}
void sendCommands()
{
std::unique_lock<std::mutex> lk(cv_m);
send (message1); 
cv.wait(lk); 
send (message2); 
cv.wait(lk); 
}

有关如何使用std::condition_variable的完整示例,请参阅此处:https://en.cppreference.com/w/cpp/thread/condition_variable/wait

最新更新