您的位置:首页 > 其它

boost::asio学习 - multithreaded programs

2010-09-27 17:26 471 查看
今天在测试boost::asio Tutorial中的 Timer.5 - Synchronising handlers in multithreaded programs 程序时,发现数据处理始终是在主线程中执行的,为了验证“If you find yourself running into these limitations, an alternative approach is to have a pool of threads calling io_service::run()”遂对timer.cpp进行了一些修改:

1.取消使用boost::asio::strand::wrap()来封装回调函数;

2.在printer::print1()中强制线程sleep(1)来检测多线程的并发处理;

完整代码如下:

timer.cpp

#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

class printer
{
public:
printer(boost::asio::io_service& io)
: strand_(io),
timer1_(io, boost::posix_time::seconds(1)),
timer2_(io, boost::posix_time::seconds(1)),
count_(0)
{
timer1_.async_wait(boost::bind(&printer::print1, this));
timer2_.async_wait(boost::bind(&printer::print2, this));
}

~printer()
{
std::cout << "Final count is " << count_ << "\n";
}

void print1()
{
std::cout << boost::this_thread::get_id() << "\n";

if (count_ < 10)
{
std::cout << "Timer 1: " << count_ << "\n";
++count_;

timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
timer1_.async_wait(boost::bind(&printer::print1, this));
}
sleep(1);
}

void print2()
{
std::cout << boost::this_thread::get_id() << "\n";

if (count_ < 10)
{
std::cout << "Timer 2: " << count_ << "\n";
++count_;

timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1));
timer2_.async_wait(boost::bind(&printer::print2, this));
}
}

private:
boost::asio::strand strand_;
boost::asio::deadline_timer timer1_;
boost::asio::deadline_timer timer2_;
int count_;
};

int main()
{
std::cout << boost::this_thread::get_id() << "\n";

boost::asio::io_service io;
printer p(io);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
io.run();
t.join();

return 0;
}


程序运行输出:

0x850e050
0x850e050
Timer 1: 0
0x850e810
Timer 2: 1
0x850e810
Timer 1: 2
0x850e050
Timer 2: 3
0x850e050
Timer 1: 4
0x850e810
Timer 2: 5
0x850e810
Timer 1: 6
0x850e050
Timer 2: 7
0x850e050
Timer 1: 8
0x850e810
Timer 2: 9
0x850e810
0x850e050

从输出结果可以看出:当多个线程运行同一个io_service::run()时,它们将并发执行该io_service上的待处理的handlers!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: