提高:: ASIO异步状态 [英] boost::asio async condition
问题描述
的想法是能够与升压:: ASIO和一个线程池来取代多线程code,在一个消费者/生产者的问题。目前,每个消费者线程等待一个的boost :: condition_variable
- 当生产者增加了一些到队列中,它调用 notify_one
/ notify_all
通知所有消费者。当你(可能)有1K +消费者现在会发生什么?线程将不能扩展!
The idea is to be able to replace multithreaded code with boost::asio and a thread pool, on a consumer/producer problem. Currently, each consumer thread waits on a boost::condition_variable
- when a producer adds something to the queue, it calls notify_one
/notify_all
to notify all the consumers. Now what happens when you (potentially) have 1k+ consumers? Threads won't scale!
我决定用的boost :: ASIO
,但后来我遇到了一个事实,即它不具备条件变量。然后 async_condition_variable
诞生了:
I decided to use boost::asio
, but then I ran into the fact that it doesn't have condition variables. And then async_condition_variable
was born:
class async_condition_variable
{
private:
boost::asio::io_service& service_;
typedef boost::function<void ()> async_handler;
std::queue<async_handler> waiters_;
public:
async_condition_variable(boost::asio::io_service& service) : service_(service)
{
}
void async_wait(async_handler handler)
{
waiters_.push(handler);
}
void notify_one()
{
service_.post(waiters_.front());
waiters_.pop();
}
void notify_all()
{
while (!waiters_.empty()) {
notify_one();
}
}
};
基本上,每个消费者会叫 async_condition_variable ::等待(...)
。然后,生产者最终将调用 async_condition_variable :: notify_one()
或 async_condition_variable :: notify_all()
。每个消费者的手柄会被调用,要么在条件或调用行为 async_condition_variable ::等待(...)
一次。这是可行的还是我疯了吗?应该执行什么样的锁(互斥)的,鉴于这将在一个线程池来运行?
Basically, each consumer would call async_condition_variable::wait(...)
. Then, a producer would eventually call async_condition_variable::notify_one()
or async_condition_variable::notify_all()
. Each consumer's handle would be called, and would either act on the condition or call async_condition_variable::wait(...)
again. Is this feasible or am I being crazy here? What kind of locking (mutexes) should be performed, given the fact that this would be run on a thread pool?
P.S:是的,这是一个多问题:)一个RFC(请求注解)。
P.S.: Yes, this is more a RFC (Request for Comments) than a question :).
推荐答案
有需要在事件发生时要做事情的清单。有一个函数的东西添加到列表中,并从该名单中删除一些功能。然后,当事件发生时,有一个池的线程现在需要做的作业列表上工作。你并不需要专门的线程等待事件。
Have a list of things that need to be done when an event occurs. Have a function to add something to that list and a function to remove something from that list. Then, when the event occurs, have a pool of threads work on the list of jobs that now need to be done. You don't need threads specifically waiting for the event.
这篇关于提高:: ASIO异步状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!