我做了发现过程在后台线程运行函数时保护共享变量:使用QMutexLocker使用QtConcurrent与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);
我以前没有把一个互斥体,以保护该函数内部的共享变量可以在后台线程运行时访问。这在我的“扫描”操作中造成了一些随机锁定。
我已经实现了互斥锁,在该函数的开头创建一个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()?
感谢
只有当您还锁定了所有其他访问它们的函数 –
感谢评论 - 因此该类中的每个函数都必须具有“QMutexLocker ml(&m_Mutex);” – PhilBot