【问题标题】:Does copy of asio::strand create a new executor?asio::strand 的副本会创建一个新的执行程序吗?
【发布时间】:2020-06-01 08:57:32
【问题描述】:

我有一份asio::io_service::strand 的副本。 复制的链及其来源是不同的执行者吗?换句话说,传递给复制链的函数和传递给源链的另一个函数是否有可能由两个不同的线程同时执行?

或者这两个链在逻辑上都是“一个链”,这意味着传递给它们的任何工作都不会与传递给它们的其他工作一起执行?

查看示例

asio::io_service ioService;

asio::io_service::strand strandFromIoService{ioService};
asio::io_service::strand strandFromStrand{strandFromIoService};

strandFromIoService.post(boost::bind(&firstFunction));
strandFromStrand.post(boost::bind(&secondFunction));

// then use a pool of threads to service io_service ...
// can firstFunction and secondFunction be executed in one time?

【问题讨论】:

    标签: c++ multithreading concurrency boost-asio


    【解决方案1】:

    答案是

    strand 类只有两个属性

    class io_service::strand
    {
    public:
      // ...
    private:
      asio::detail::strand_service& service_;
      asio::detail::strand_service::implementation_type impl_;
    };
    

    impl_ 是指向strand_impl 的指针:

    typedef strand_impl* implementation_type;
    

    strand 类中也没有用户定义的复制构造函数。 它是strand_impl,它包含que、mutex、counter 和所有与多线程相关的东西。而且这些东西在strand 副本上没有改变,因为strand 只有一个指向它的指针,并且只复制了一个指针(没有说 io_service 引用,但这个引用显然对链复制没有影响)

    因此,副本链和源链在逻辑上是相同的链。它们代表同一个执行者。

    这也符合我的实验。问题示例中的 firstFunctionsecondFunction 确实由 2 个线程按顺序执行。

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 1970-01-01
      • 2020-10-03
      • 2021-11-22
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      相关资源
      最近更新 更多