1 c++ boost asynchronous asio c++98
注意:这是针对C++98的
我正在尝试开发一个在主程序后台运行的简单计时器/计数器。
我以前没有使用过异步计时器,并且我一直在尝试遵循 boost 教程来了解如何执行此操作,但它们似乎仍然阻止了我的主要功能。我稍微修改了 boost 网站上的Timer.3来进行实验。
本质上,通过下面的程序,我想做的是:
主程序
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出
0
PRINT
1
PRINT
2
PRINT
3
PRINT
4
PRINT
PRINT
Final count is 5
TEST ABC
Run Code Online (Sandbox Code Playgroud)
我希望我的输出看起来像:
TEST ABC
0
PRINT
1
PRINT
2
PRINT
3
PRINT
4
PRINT
PRINT
Final count is 5
Run Code Online (Sandbox Code Playgroud)
为了解构手头的任务,我将从一个简单的 C++98 实现开始。
我们将把它清理为现代 C++,然后用 Asio 替换。
您将看到 Asio 不需要线程,这很好。但我们必须回到过去,用 C++98 取代现代 C++。
最后,您将了解加入现代 C++ 的所有原因,以及如何以可以轻松管理复杂性的方式组织代码。
这是我在 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);
}
Run Code Online (Sandbox Code Playgroud)
印刷
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
Run Code Online (Sandbox Code Playgroud)
嗯,上面的内容确实很难说是 C++。它实际上是“相同的”,但在 C 中使用printf. 以下是 C++11 的改进方式:
#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();
}
Run Code Online (Sandbox Code Playgroud)
相同的输出,但更清晰。此外,还有更多保证。我们可以仅使用 分离线程th.detach(),或者将我们想要的任何参数传递给线程函数,而不是舞蹈void*。
C++17
C++14 添加了更多内容(计时文字),C++17 仅添加了少量内容(此处使用的折叠表达式具有自然的 ostream 访问权限):
仅在 Coliru 上生活 。请注意,这已降至 35 LoC
转换为 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;
};
Run Code Online (Sandbox Code Playgroud)
这对我来说看起来很不言自明。整个程序现在可以归结为:
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();
}
Run Code Online (Sandbox Code Playgroud)
观看Coliru 直播。
如果我们使用限制执行,我们可以进一步简化它
run_for(这样我们就不必处理退出问题):Live On Coliru,低至 44 LoCRun Code Online (Sandbox Code Playgroud)#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); }
没有 lambda。好吧,我们可以使用boost::bind或者自己编写一些类。你选择你的毒药,我选择混合物:
boost::bind因为它是那个时代的工具(我们说的是20年前)std::function不是callback.这一切都变得不那么优雅,但基本上可以看出是同一件事:
#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();
}
Run Code Online (Sandbox Code Playgroud)
输出仍然相同,值得信赖
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 Code Online (Sandbox Code Playgroud)
与之前的相同转换
run_for也可以应用在这里,但我们现在必须链接 Boost Chrono 因为std::chrono不存在:Live On Coliru,仍然是 56 LoC
| 归档时间: |
|
| 查看次数: |
2648 次 |
| 最近记录: |