c++ - C++ boost异步定时器与程序并行运行
问题描述
注意:这是针对 C++98
我正在尝试开发一个在我的主程序后台运行的简单计时器/计数器。
我以前没有使用过异步计时器,我一直在尝试按照 boost 教程来了解如何做到这一点,但它们似乎仍然阻止了我的主要功能。我稍微修改了 来自 boost 网站的Timer.3以进行实验。
本质上,通过下面的程序,我想要做的是:
- 运行主程序
- 执行 testRun() 计数为 5
- 在 testRun() 计数的同时,在 main 中打印“TEST ABC”。
主文件
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
void print(const boost::system::error_code& /*e*/, boost::asio::deadline_timer* t, int* count)
{
if (*count < 5)
{
std::cout << *count << std::endl;
++(*count);
t->expires_at(t->expires_at() + boost::posix_time::seconds(1)); // every 1 second advance
t->async_wait(boost::bind(print, boost::asio::placeholders::error, t, count));
}
std::cout << " PRINT " << std::endl;
}
void testRun()
{
boost::asio::io_service io;
int count = 0;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(2)); // start io object (function) after 2 seconds.
t.async_wait(boost::bind(print, boost::asio::placeholders::error, &t, &count));
io.run();
std::cout << "Final count is " << count << std::endl;
}
int main()
{
testRun();
std::cout << " TEST ABC " << std::endl;
return 0;
}
输出
0
PRINT
1
PRINT
2
PRINT
3
PRINT
4
PRINT
PRINT
Final count is 5
TEST ABC
我希望我的输出看起来像:
TEST ABC
0
PRINT
1
PRINT
2
PRINT
3
PRINT
4
PRINT
PRINT
Final count is 5
解决方案
为了解构手头的任务,我将从一个简单的 C++98 实现开始。
我们会将其清理为现代 C++,然后替换为 Asio。
您会看到 Asio 不需要线程,这很好。但是我们必须回到过去,用 C++98 取代现代 C++。
最后,您将看到加入现代 C++ 的所有理由,以及如何以可以轻松管理复杂性的方式组织代码。
C++98
以下是我在 c++98 中的写法:
#include <pthread.h>
#include <iostream>
#include <sstream>
#include <unistd.h>
static pthread_mutex_t s_mutex = {};
static bool s_running = true;
static bool is_running(bool newvalue) {
pthread_mutex_lock(&s_mutex);
bool snapshot = s_running;
s_running = newvalue;
pthread_mutex_unlock(&s_mutex);
return snapshot;
}
static bool is_running() {
pthread_mutex_lock(&s_mutex);
bool snapshot = s_running;
pthread_mutex_unlock(&s_mutex);
return snapshot;
}
static void output(std::string const& msg) {
pthread_mutex_lock(&s_mutex);
std::cout << msg << "\n";
pthread_mutex_unlock(&s_mutex);
}
static void* count_thread_func(void*) {
for (int i = 0; i < 5; ++i) {
::sleep(1);
std::ostringstream oss;
oss << "COUNTER AT " << (i+1);
output(oss.str());
}
is_running(false);
return NULL;
}
int main() {
pthread_t thr = {0};
pthread_create(&thr, NULL, &count_thread_func, NULL);
while (is_running()) {
::usleep(200000);
output("TEST_ABC");
}
pthread_join(thr, NULL);
}
印刷
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
COUNTER AT 1
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
COUNTER AT 2
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
COUNTER AT 3
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
COUNTER AT 4
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
COUNTER AT 5
TEST_ABC
C++11
好吧,上面真的几乎不是 C++。它实际上与 C 中的“相同”但更方便printf
。以下是 C++11 改进的方式:
- std::thread、std::atomic_bool、std::chono、std::this_thread、std::to_string、std::mutex/lock_guard、更好的初始化。
#include <thread>
#include <iostream>
#include <chrono>
#include <mutex>
#include <atomic>
using std::chrono::milliseconds;
using std::chrono::seconds;
static std::mutex s_mutex;
static std::atomic_bool s_running {true};
static void output(std::string const& msg) {
std::lock_guard<std::mutex> lk(s_mutex);
std::cout << msg << "\n";
}
static void count_thread_func() {
for (int i = 0; i < 5; ++i) {
std::this_thread::sleep_for(seconds(1));
output("COUNTER AT " + std::to_string(i+1));
}
s_running = false;
}
int main() {
std::thread th(count_thread_func);
while (s_running) {
std::this_thread::sleep_for(milliseconds(200));
output("TEST_ABC");
}
th.join();
}
相同的输出,但更清晰。此外,还有更多的保证。我们可以用 just 分离线程th.detach()
,或者将我们想要的任何参数传递给线程函数,而不是void*
舞蹈。
C++17
C++14 增加了一些(计时文字),C++17 只是略微增加了一些(这里使用的折叠表达式具有自然的 ostream 访问):
仅住在 Coliru 。请注意,这已降至 35 LoC
回到 C++1x:ASIO
翻译成 ASIO 完全消除了对线程的需求,用异步计时器代替了睡眠。
因为没有线程,所以不必有任何锁定,从而简化了生活。
我们不需要“正在运行”标志,因为如果需要,我们可以停止服务或取消计时器。
整个程序归结为:
由于我们将不得不按间隔运行任务,因此我们将其机制放在一个简单的类中,因此我们不必重复它:
// simple wrapper that makes it easier to repeat on fixed intervals
struct interval_timer {
interval_timer(boost::asio::io_context& io, Clock::duration i, Callback cb)
: interval(i), callback(cb), timer(io)
{}
void run() {
timer.expires_from_now(interval);
timer.async_wait([=](error_code ec) {
if (!ec && callback())
run();
});
}
void stop() {
timer.cancel();
}
private:
Clock::duration const interval;
Callback callback;
boost::asio::high_resolution_timer timer;
};
这对我来说看起来很不言自明。整个程序现在归结为:
int main() {
boost::asio::io_context io;
interval_timer abc { io, 200ms, [] {
std::cout << "TEST_ABC" << std::endl;
return true;
} };
interval_timer counter { io, 1s, [&abc, current=0]() mutable {
std::cout << "COUNTER AT " << ++current << std::endl;
if (current < 5)
return true;
abc.stop();
return false;
} };
abc.run();
counter.run();
io.run();
}
看到它住在 Coliru 上。
如果我们使用
run_for
限制执行,我们可以进一步简化它(所以我们不必处理自己退出):Live On Coliru,低至 44 LoC#include <boost/asio.hpp> #include <iostream> #include <chrono> #include <functional> using namespace std::chrono_literals; using Clock = std::chrono::high_resolution_clock; using Callback = std::function<void()>; using boost::system::error_code; // simple wrapper that makes it easier to repeat on fixed intervals struct interval_timer { interval_timer(boost::asio::io_context& io, Clock::duration i, Callback cb) : interval(i), callback(cb), timer(io) { run(); } private: void run() { timer.expires_from_now(interval); timer.async_wait([=](error_code ec) { if (!ec) { callback(); run(); } }); } Clock::duration const interval; Callback callback; boost::asio::high_resolution_timer timer; }; int main() { boost::asio::io_context io; interval_timer abc { io, 200ms, [] { std::cout << "TEST_ABC" << std::endl; } }; interval_timer counter { io, 1s, [current=0]() mutable { std::cout << "COUNTER AT " << ++current << std::endl; } }; io.run_for(5s); }
回到 C++98
没有 lambda。好的,我们可以boost::bind
自己使用或编写一些类。你选你的毒药,我选一个混合物:
boost::bind
因为它是那个时代的工具(我们说的是 20 年前)- 使用虚方法而不是
std::function
forcallback
。 - lambda 捕获已替换为显式成员变量。
这一切都变得不那么优雅了,但基本上可以识别为同一件事:
#include <boost/asio.hpp>
#include <iostream>
#include <boost/bind.hpp>
using boost::posix_time::seconds;
using boost::posix_time::millisec;
typedef boost::posix_time::microsec_clock Clock;
using boost::system::error_code;
// simple wrapper that makes it easier to repeat on fixed intervals
struct interval_timer {
interval_timer(boost::asio::io_context& io, millisec i)
: interval(i), timer(io)
{ run(); }
virtual bool callback() = 0;
void run() {
timer.expires_from_now(interval);
timer.async_wait(boost::bind(&interval_timer::on_timer, this, boost::asio::placeholders::error()));
}
void stop() {
timer.cancel();
}
private:
void on_timer(error_code ec) {
if (!ec && callback())
run();
}
millisec const interval;
boost::asio::deadline_timer timer;
};
int main() {
boost::asio::io_context io;
struct abc_timer : interval_timer {
abc_timer(boost::asio::io_context& io, millisec i) : interval_timer(io, i) {}
virtual bool callback() {
std::cout << "TEST_ABC" << std::endl;
return true;
}
} abc(io, millisec(200));
struct counter_timer : interval_timer {
counter_timer(boost::asio::io_context& io, millisec i, interval_timer& abc)
: interval_timer(io, i), abc(abc), current(0) {}
virtual bool callback() {
std::cout << "COUNTER AT " << ++current << std::endl;
if (current < 5)
return true;
abc.stop();
return false;
}
private:
interval_timer& abc;
int current;
} counter(io, millisec(1000), abc);
io.run();
}
输出仍然是一样的可信赖
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
COUNTER AT 1
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
COUNTER AT 2
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
COUNTER AT 3
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
COUNTER AT 4
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
TEST_ABC
COUNTER AT 5
与之前相同的转换
run_for
也可以在这里应用,但是我们现在必须链接 Boost Chrono 因为std::chrono
不存在:Live On Coliru,仍然是 56 LoC
推荐阅读
- reactjs - React styled-component 按钮没有获得焦点
- amazon-web-services - 如何在 AWS 上将 IP 列入白名单
- python - 将 .lower() 函数应用于列表中所有单词情况的字符串
- cloud - 使用 Aws 创建基于 Web 的数据输入应用程序
- typescript - 打字稿泛型中需要期望
- javascript - 将 App.Js 导入节点时出现 BABEL_PARSE_ERROR
- selenium - 为什么我不能使用变量?[科特林]
- angular-material - 如何仅使用十六进制值创建角度材质主题?
- amcharts4 - AMCharts4 XYChart 隐藏系列时没有预缩放
- ios - Apple 是如何在其 iOS 图书应用中实现书签功能的?