Qt Blocking Master example
了解如何使用qt进行串行通信。在本例中,串行通信是以同步方式进行的,因此,为了保持GUI的响应性,将创建一个单独的(非GUI)线程来处理串行通信。我不明白的是在负责通信的线程中使用互斥体的部分(即
MasterThread
注意,在主线程中调用transaction()方法,但是
成员在不同的线程中同时读写,因此
void MasterThread::transaction(const QString &portName, int waitTimeout, const QString &request)
{
QMutexLocker locker(&mutex);
this->portName = portName;
this->waitTimeout = waitTimeout;
this->request = request;
if (!isRunning())
start();
else
cond.wakeOne();
}
[主线程运行方法]
void MasterThread::run()
{
bool currentPortNameChanged = false;
mutex.lock();
QString currentPortName;
if (currentPortName != portName) {
currentPortName = portName;
currentPortNameChanged = true;
}
int currentWaitTimeout = waitTimeout;
QString currentRequest = request;
mutex.unlock();
同时处理获取数据。注意,当
-
线程(创建于
Dialog
-
我对上面引述的最后一句话(即“在任何情况下……”)更加困惑。“[另一个]进程获取数据”是什么意思?我们这里只有一个进程(即整个应用程序)和两个线程(一个用于GUI,一个用于串行通信),而这两个线程没有共享数据,这不是真的吗?为什么螺纹安全
QString