對于這個問題,是否有比使用在回圈中檢查的全域布爾標志創建類似自旋鎖的結構更好的答案?
bool isRunning = true;
void busyLoop()
{
for (;;) {
if (!isRunning)
continue;
// ...
}
}
int main()
{
// ...
QPushButton *startBusyLoopBtn = new QPushButton("start busy loop");
QObject::connect(startBusyLoopBtn, QPushButton::clicked, [](){ busyLoop(); });
QPushButton *startPauseBtn = new QPushButton("start/pause");
QObject::connect(startPauseBtn, QPushButton::clicked, [](){ isRunning = !isRunning; });
// ...
}
首先,我們在檢查標志時浪費了 CPU 時間。其次,我們需要兩個單獨的按鈕才能使該方案起作用。我們如何使用 Qt 的槽信號機制來獲得更簡單的解決方案?
uj5u.com熱心網友回復:
您可以使用std::condition_variable:
std::mutex mtx;
std::condition_variable cv_start_stop;
std::thread thr([&](){
/**
* this thread will notify and unpause the main loop 3 seconds later
*/
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
cv_start_stop.notify_all();
});
bool paused = true;
while (true)
{
if (paused)
{
std::unique_lock<std::mutex> lock(mtx);
cv_start_stop.wait(lock); // this will lock the thread until notified.
std::cout << "thread unpaused\n";
paused = false;
}
std::cout << "loop goes on until paused\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
這不會殘酷地檢查標志是否繼續,相反,它會使執行緒進入睡眠狀態,直到收到通知。
您將簡單paused = true;地暫停和/cv_start_stop.notify_one();或cv_start_stop.notify_all();取消暫停。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/382089.html
