FreeOZ论坛

标题: boost: 求教 [打印本页]

作者: GPS    时间: 20-4-2010 15:23
标题: boost: 求教
#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后, 输出的结果就不会同步,可是,我怎么得不到这个结果。 到底我是错哪里了?
作者: GPS    时间: 20-4-2010 16:01
标题: 似乎搞懂了点。
printer p(io)后, 会生成两个tasks(  timer1_ 和timer2_ 的wait, )挂在 io 上,
主线程和副线程各调用io.run,及各从io上取得一个task来运行,当没有task时,io.run结束。
不知道对否。




欢迎光临 FreeOZ论坛 (https://www.freeoz.org/ibbs/) Powered by Discuz! X3.2