要在某个事件上等待某个时间或,我会使用std::mutex 和std::condition_variable 的组合,特别是std::condition_variable::wait_for() 来等待超时或信号更改的东西。
用于演示的最小示例程序:
#include <atomic>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
// a thread-shared flag to signal exit
std::atomic<bool> exitThread = false;
// a mutex to sync. inter-thread communication
std::mutex mtxAlert;
// a condition variable to signal changed data
std::condition_variable sigAlert;
// the data of inter-thread communication
bool alert = false;
void timerThread()
{
// the timeout for timer thread
auto timeout = 100ms;
// runtime loop
while (!exitThread) {
// lock mutex (preparation to wait in cond. var.)
std::unique_lock<std::mutex> lock(mtxAlert);
// unlock mutex and wait for timeout or signaled alert
sigAlert.wait_for(lock, timeout, []() { return alert || exitThread; });
// mutex is locked again
// check why wait_for() exited
if (exitThread) {
std::cout << "Timer thread exiting...\n";
return;
} else if (alert) {
std::cout << "Timer was interrupted due to alert.\n";
alert = false;
} else {
std::cout << "Timer achieved time-out.\n";
}
}
}
int main()
{
std::thread threadWait(&timerThread);
// wait a bit
std::cout << "main(): Waiting 300ms...\n";
std::this_thread::sleep_for(300ms);
// sim. interrupt
std::cout << "main(): Sim. interrupt.\n";
{ std::lock_guard<std::mutex> lock(mtxAlert);
alert = true;
}
sigAlert.notify_all();
// wait a bit
std::cout << "main(): Waiting 50 ms...\n";
std::this_thread::sleep_for(50ms);
// sim. interrupt
std::cout << "main(): Sim. interrupt.\n";
{ std::lock_guard<std::mutex> lock(mtxAlert);
alert = true;
}
sigAlert.notify_all();
// wait a bit
std::cout << "main(): Waiting 50 ms...\n";
std::this_thread::sleep_for(50ms);
// exiting application
exitThread = true;
sigAlert.notify_all();
threadWait.join();
// done
std::cout << "Done.\n";
}
输出:
main(): Waiting 300ms...
Timer achieved time-out.
Timer achieved time-out.
main(): Sim. interrupt.
main(): Waiting 50 ms...
Timer was interrupted due to alert.
main(): Sim. interrupt.
main(): Waiting 50 ms...
Timer was interrupted due to alert.
Timer thread exiting...
Done.
Live Demo on coliru
OP 根据评论声称此示例未在 cygwin 上正确编译。我试过了,可以确认我修复的一些小问题:
添加了缺少的#include <mutex>
-
std::atomic<bool> exitThread = false;的初始化改为
std::atomic<bool> exitThread(false);
当我使用g++ 和g++ -std=c++14 编译时,我得到了这个。 (看来-std=c++14是我g++的默认值。)
当我改用g++ -std=c++17 时,我没有收到任何投诉。我坚信这与copy-elision 有关,g++ 适用于-std=c++17,但不是之前的。
但是,这是我在cygwin64cygwin64 上使用 Windows 10 笔记本电脑上经过稍微审查的代码的示例会话:
$ g++ --version
g++ (GCC) 7.4.0
$
$ cat >testCondVar.cc <<'EOF'
> #include <atomic>
> #include <condition_variable>
> #include <iostream>
> #include <mutex>
> #include <thread>
> #include <chrono>
> using namespace std::chrono_literals;
>
> // a thread-shared flag to signal exit
> std::atomic<bool> exitThread(false);
>
> // a mutex to sync. inter-thread communication
> std::mutex mtxAlert;
> // a condition variable to signal changed data
> std::condition_variable sigAlert;
> // the data of inter-thread communication
> bool alert = false;
>
> void timerThread()
> {
> // the timeout for timer thread
> auto timeout = 100ms;
> // runtime loop
> while (!exitThread) {
> // lock mutex (preparation to wait in cond. var.)
> std::unique_lock<std::mutex> lock(mtxAlert);
> // unlock mutex and wait for timeout or signaled alert
> sigAlert.wait_for(lock, timeout, []() { return alert || exitThread; });
> // mutex is locked again
> // check why wait_for() exited
> if (exitThread) {
> std::cout << "Timer thread exiting...\n";
> return;
> } else if (alert) {
> std::cout << "Timer was interrupted due to alert.\n";
> alert = false;
> } else {
> std::cout << "Timer achieved time-out.\n";
> }
> }
> }
>
> int main()
> {
> std::thread threadWait(&timerThread);
> // wait a bit
> std::cout << "main(): Waiting 300ms...\n";
> std::this_thread::sleep_for(300ms);
> // sim. interrupt
> std::cout << "main(): Sim. interrupt.\n";
> { std::lock_guard<std::mutex> lock(mtxAlert);
> alert = true;
> }
> sigAlert.notify_all();
> // wait a bit
> std::cout << "main(): Waiting 50 ms...\n";
> std::this_thread::sleep_for(50ms);
> // sim. interrupt
> std::cout << "main(): Sim. interrupt.\n";
> { std::lock_guard<std::mutex> lock(mtxAlert);
> alert = true;
> }
> sigAlert.notify_all();
> // wait a bit
> std::cout << "main(): Waiting 50 ms...\n";
> std::this_thread::sleep_for(50ms);
> // exiting application
> exitThread = true;
> sigAlert.notify_all();
> threadWait.join();
> // done
> std::cout << "Done.\n";
> }
> EOF
$
编译并启动:
$ g++ -std=c++14 -o testCondVar testCondVar.cc
$ ./testCondVar
main(): Waiting 300ms...
Timer achieved time-out.
Timer achieved time-out.
main(): Sim. interrupt.
main(): Waiting 50 ms...
Timer was interrupted due to alert.
main(): Sim. interrupt.
main(): Waiting 50 ms...
Timer was interrupted due to alert.
Timer thread exiting...
Done.
$
注意:
此示例至少需要 C++14 的唯一原因是使用了 std::chrono_literals,它可以使用例如300ms.
没有std::chrono_literals,这可以写成std::chrono::milliseconds(300)(诚然不太方便)。分别替换所有std::chrono_literals,我也能够使用-std=c++11 编译和运行示例。