我使用 QtConcurrent 在后台线程中执行发现过程:
// Start the discover process in the background thread so it doesn't block the gui
*m_Future = QtConcurrent::run(this, &Controller::StartDiscover);
m_Watcher->setFuture(*m_Future);
我以前没有放置 Mutex 来保护该函数内的共享变量,这些变量可以在后台线程运行时访问。这在我的“扫描”操作期间导致了一些随机锁定。
我现在已经实现了互斥锁,在该函数的开头创建了一个 QMutexLocker。
int Controller::StartDiscover() {
// Lock mutex
QMutexLocker ml(&m_Mutex);
// Zero
m_NumberBoundDevices = 0;
// Update to scanning
m_Status = Scanning;
// Discover slaves
int numberAttachedSlaves = m_Client->DiscoverSlaves();
m_Client->setTimeout(20000); // 20 Second Timeout
if ( numberAttachedSlaves > 0 ) {
int cnt = 0;
while ( cnt < 3 ) {
for (int slave = 1 ; slave <= numberAttachedSlaves ; slave++ ) {
// Get information about this slave
QDBusPendingReply<uchar> reply = m_Client->SlaveService(slave,m_Packet);
reply.waitForFinished(); // Wait for it to complete
if (!reply.isValid()) {
m_Client->SlaveService(slave,m_Packet);
reply.waitForFinished();
}
if ( reply.isError() ) {
QString errorMsg = reply.reply().errorMessage();
}
}
// Increment counter
cnt++;
}
}
// Update
m_NumberBoundDevices = numberAttachedSlaves;
// Return the number of devices discovered
return numberAttachedSlaves;
}
这会保护函数内的所有共享变量吗?或者,我应该在每个 m_* 变量周围显式使用 QMutex.lock() 和 unlock() 吗?
谢谢