![](/img/trans.png)
[英]How can I make my QThread block and wait for a function called from the main thread to return a value?
[英]How can I protect a QThread function so it will not be called again until finished its previous work?
我使用的是QThread,在它的run
方法中,我有一個計時器,該計時器調用一個函數,該函數執行一些耗時的繁重操作。 通常大於觸發計時器的時間間隔(但並非總是如此)。
我需要保護此方法,以便僅在完成先前的工作后才能調用它。
這是代碼:
NotificationThread::NotificationThread(QObject *parent)
: QThread(parent),
bWorking(false),
m_timerInterval(0)
{
}
NotificationThread::~NotificationThread()
{
;
}
void NotificationThread::fire()
{
if (!bWorking)
{
m_mutex.lock(); // <-- This is not protection the GetUpdateTime method from invoking over and over.
bWorking = true;
int size = groupsMarkedForUpdate.size();
if (MyApp::getInstance()->GetUpdateTime(batchVectorResult))
{
bWorking = false;
emit UpdateNotifications();
}
m_mutex.unlock();
}
}
void NotificationThread::run()
{
m_NotificationTimer = new QTimer();
connect(m_NotificationTimer,
SIGNAL(timeout()),
this,
SLOT(fire(),
Qt::DirectConnection));
int interval = val.toInt();
m_NotificationTimer->setInterval(3000);
m_NotificationTimer->start();
QThread::exec();
}
// This method is invoked from the main class
void NotificationThread::Execute(const QStringList batchReqList)
{
m_batchReqList = batchReqList;
start();
}
您可能總是有一個線程需要運行連接到onDone信號的方法,該信號會警告所有訂閱者它已完成。 這樣一來,您就不會遇到與雙重鎖定檢查和內存重新排序相關的問題。 保持每個線程的運行狀態。
我假設您想保護自己的線程免受來自另一個線程的調用。 我對嗎? 如果是,那么..
這就是QMutex的目的。 QMutex提供了一個“鎖定”線程直到“解鎖”接口,從而序列化對該線程的訪問。 您可以選擇解鎖線程,直到完成其工作為止。 但是使用它需要您自擔風險。 如果使用不正確,QMutex會出現自己的問題。 有關更多信息,請參考文檔。
但是還有很多解決問題的方法,例如@Beached提出了一種更簡單的解決問題的方法。 如果完成,您的QThread實例將發出信號。 或bool isDone
在線程內創建一個bool isDone
,如果完成則為true
,否則為false
。 如果是true
那么調用該方法是安全的。 但是請確保不要在擁有它的線程之外操作isDone
。 我建議您僅在QThread中操作isDone
。
這是課程文檔: 鏈接
大聲笑,我嚴重誤解了你的問題。 抱歉。 看來您已經通過bWorking
完成了我的第二個建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.