如何运行两个不同的while循环而不破坏一个?
该程序通过while循环从可编程控制器( PLC )中采集两种不同的值。
这个收集应该在同时进行,但是当我试图运行两个循环时,它们会中断.第一个循环只是停止返回任何值,而第二个循环正在运行。
发布于 2020-11-30 20:49:49
您的程序需要从两个设备连接、读取和断开连接,但是一次只能打开一个连接。因此,这些连接是相互排斥的。你可以用一个互斥物来做这个。
您的代码建议,一个连接应该通过一定的超时无限期地轮询,而另一个连接应该根据请求通过一个按钮进行轮询。我只需将两者放在一个插槽中,一个按下按钮,另一个按定时器,然后用互斥物保护它们。
大纲:
class MainProgram : QObject {
// Other stuff
private slots:
void on_pushCheck_clicked();
void readPeriodically();
private:
QMutex m_mutex;
QTimer *m_timer;
};
void MainProgram::MainProgram()
{
// other stuff
m_timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, &MainProgram::readPeriodically);
m_timer->setInterval(2000);
m_timer->start();
}
void MainProgram::on_pushCheck_clicked()
{
QMutexLocker l(&m_mutex);
// Read from device 1
}
void MainProgram::readPeriodically()
{
QMutexLocker l(&m_mutex);
// Read from device 2
}这假设读取将非常快,因为UI在此期间被阻塞。如果不是这样,则可以将读取代码放入反向工作线程中。此方法是异步的,触发读取,稍后将得到结果:
class DeviceReader : QObject {
public:
void readDevice1();
void readDevice2();
signals:
void device1Data(int);
void device2Data(int);
private:
Q_INVOKABLE void doReadDevice1();
Q_INVOKABLE void doReadDevice2();
private:
QMutex m_mutex;
};
void DeviceReader::readDevice1()
{
// Cross thread boundary
QMetaObject::invokeMethod(this, "doReadDevice1", Qt::QueuedConnection);
}
void DeviceReader::doReadDevice1()
{
QMutexLocker l(&m_mutex);
// Read from device 1
emit device1Data(1);
}
// similar for device 2
MainProgram::MainProgram() {
DeviceReader *r = new DeviceReader;
QThread *t = new QThread;
r->moveToThread(t);
// Connect signals for starting reads, or call them as necessary
// Connect signal to deleteLater on thread when app closes
// e.g. QApplication::aboutToQuit
// The worker object does not have a "working" method.
// It will just listen to events (signals) through the thread's exec loop
t->start();
}https://stackoverflow.com/questions/65077105
复制相似问题