我在多线程C++程序中使用boost::asio::thread_pool,我需要知道队列中当前执行了多少任务来提交新任务。
// async thread, pass pool_ by ref
static void somecallback(boost::asio::thread_pool& pool) {
if (pool.%queue_size% < %some limit%) {
boost::asio::post(pool, my_task);
} else {
std::cerr << "queue overflowed!" << std::endl;
}
}
// main thread
class A {
public:
A():pool_(4){};
~A();
// some logic
...
private:
boost::asio::thread_pool pool_;
}
A::~A(){
pool_.join();
}
是否有可能以某种方式获得queue_size参数及其值的模拟?
没有这样的功能。另请注意,在 Asio 模型中没有“任务”的概念。线程池实现不是通用的,但它通过为异步操作运行(中间处理程序)的线程丰富了执行上下文。
直接连接到池的执行器的处理程序只是生态系统的一小部分,也是执行上下文的典型负载。
因此,在应用程序级别跟踪“任务”是最有意义的,例如使用原子共享计数器,该计数器在任务启动/退出时递增/递减。举个简单的例子
住在科里鲁
post
打印例如
#include <boost/asio.hpp>
static std::atomic_int tid_gen{};
thread_local int const tid = tid_gen++;
namespace task_counter {
static std::atomic_uint s_pending{};
struct guard {
guard() noexcept { ++s_pending; }
~guard() noexcept { if (armed_) --s_pending; }
guard(guard&& rhs) noexcept : armed_(std::exchange(rhs.armed_, false)) {}
guard& operator=(guard&& rhs) { std::swap(armed_, rhs.armed_); return *this; }
unsigned current() const { return s_pending; }
private:
bool armed_ = true;
};
}
auto make_task(char const* id) {
return [=, g=task_counter::guard{}] { //
printf("t:%d\ttask:%s\tpending:%i\n", tid, id, g.current());
};
}
int main(){
{
boost::asio::thread_pool p{8};
printf("t:%d\ttask:%s\tpending:%i\n", tid, __FUNCTION__, task_counter::s_pending.load());
auto ex = p.get_executor();
for (auto av : {"foo", "bar", "qux", "quux", "corge", "grault", "garply", "waldo", //
"sbb", "one", "dhk", "dhhk", "pbetr", "tenhyg", "tnecyl", "jnyqb"})
post(ex, make_task(av));
p.join();
}
assert(!task_counter::s_pending);
}