为了解构手头的任务,我将从简单的 C++98 实现开始。
我们会将其清理为现代 C++,然后替换为 Asio。
您会看到 Asio 不需要线程,这很好。但我们必须回到过去,用 C++98 取代现代 C++。
最后,您将看到加入现代 C++ 的所有理由,以及如何以一种可以轻松管理复杂性的方式组织代码。
C++98
这是我在 c++98 中的写法:
Live On Coliru
#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++。它实际上与printf 在 C 中“相同”但更方便。以下是 C++11 改进的方式:
- std::thread、std::atomic_bool、std::chono、std::this_thread、std::to_string、std::mutex/lock_guard、更好的初始化。
Live On Coliru
#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();
}
输出相同,但更清晰。此外,还有更多的保证。我们可以只使用th.detach() 分离线程,或者将我们想要的任何参数传递给线程函数,而不是void* 舞蹈。
C++17
C++14 增加了一些(计时字面量),C++17 只是略微增加了一些(折叠
此处使用的表达式具有自然的 ostream 访问权限):
Live On 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();
}
看到它Live On 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 年前)
- 对
callback 使用虚拟方法而不是std::function。
- 已将 lambda 捕获替换为显式成员变量。
这一切都变得不那么优雅了,但基本上可以识别为同一件事:
Live On Coliru
#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