繁体   English   中英

在多线程程序中使用多个async_wait

[英]Using multiple async_wait in a multithreaded program

我有以下程序,取自http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/tutorial/tuttimer5.html

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


class Printer {
private:
  boost::asio::io_service::strand strand_;
  boost::asio::deadline_timer timer1_;
  boost::asio::deadline_timer timer2_;
  int count_;

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_ << std::endl;
  }

  void print1() {
    if(count_ < 10) {
      std::cout << "Timer 1: " << count_ << std::endl;
      ++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_ << std::endl;
      ++count_;

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

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;
}

据我所理解,

timer1_.async_wait(strand_.wrap(boost::bind(&Printer::print1, this)));
timer2_.async_wait(strand_.wrap(boost::bind(&Printer::print2, this)));

确保print1print2永远不会同时运行。 但是,我不了解的是如何在main函数中解决问题。

我认为

boost::thread t(boost::bind(&boost::asio::io_service::run, &io));

在主线程io.run()之外创建一个新线程,并且t.join()阻塞主线程,直到t完成。

我不明白的是,什么工作分配给线程t ,什么工作分配给主线程。 此外,在两个不同的线程中具有两个async_wait有什么意义?

谢谢,

在现实世界中,工作分配并不是很明显。 您可以从多个线程调用boost::asio::io_service::run() ,这些线程将分担工作负载。 根据文档 ,“ 池中等待的所有线程都是等效的,io_service可以选择其中任何一个来调用处理程序。

在这种情况下,让异步在两个不同的线程上等待更像是一种练习,以展示其工作原理,而不是具有明确定义的用例。

我不明白的是,绞线确保永远不会同时运行。 因此,让两个线程运行这些线程有什么意义?

请参阅为什么在使用boost :: asio时为什么每个连接都需要绞线? 是的,单线程将是一个隐式线程。

如果单个线程不足以满足您的需求,则使用更多线程。

计时器有不同的用途, 不是每个线程一个。 (在io_service任务中没有线程相似性的概念。除非您像上述那样强制使用隐式链,否则Strands是没有线程相似性的逻辑概念)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM