找回密码
 FreeOZ用户注册
查看: 1380|回复: 1
打印 上一主题 下一主题

[论坛技术] boost: 求教

[复制链接]
跳转到指定楼层
1#
发表于 20-4-2010 15:23:08 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?FreeOZ用户注册

x
#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(strand_.wrap(boost::bind(&printer::print1, this)));
    timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
  }

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

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

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

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

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

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

int main()
{
  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;
}

上面是boost::asio的范例(http://www.boost.org/doc/libs/1_ ... /tuttimer5/src.html)。
演示用strand来同步线程。
我搞不懂的是,有两个线程调用io.run,一个是主线程,一个是分线程(t).
是不是一个会调用printer::print1(), 另一个调用printer::print2()? 那么谁调用print1,谁用print2? 在哪里说明的。
还是两个线程都调用两个printer1/2?
看起来象后者,那么,为了演示的目的,是不是只要一个print1()就可以了?
如果是这样,那么当去掉print2及strand后, 输出的结果就不会同步,可是,我怎么得不到这个结果。 到底我是错哪里了?
回复  

使用道具 举报

2#
 楼主| 发表于 20-4-2010 16:01:03 | 只看该作者

似乎搞懂了点。

printer p(io)后, 会生成两个tasks(  timer1_ 和timer2_ 的wait, )挂在 io 上,
主线程和副线程各调用io.run,及各从io上取得一个task来运行,当没有task时,io.run结束。
不知道对否。
回复  

使用道具 举报

您需要登录后才可以回帖 登录 | FreeOZ用户注册

本版积分规则

小黑屋|手机版|Archiver|FreeOZ论坛

GMT+10, 30-4-2024 11:06 , Processed in 0.011941 second(s), 17 queries , Gzip On, Redis On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表