Does copy of asio::strand create a new executor?
Asked Answered
B

1

7

I have a copy of asio::io_service::strand. Are the copied strand and its source different executors? In other words is it possible that a function passed to the copied strand and another function passed to the source strand will be executed in the same time by two different threads?

Or are both such strands logically "one strand" meaning no work passed to any of them will be executed together with other work passed to them?

See example

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?
Binate answered 17/2, 2020 at 12:14 Comment(0)
B
6

The answer is no.

strand class has two attributes only

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

impl_ is a pointer to strand_impl:

typedef strand_impl* implementation_type;

There is also no user-defined copy constructor in strand class. It is strand_impl, which contains que, mutex, counter and all stuff related to multithreading. And this stuff is not changed on strand copy since strand has only a pointer to it and only pointer is copied (saying nothing about io_service reference, but this reference has obviously no impact on strand copy)

Therefore a copy and a source strands are logically the same strand. They represent the same executor.

This also matches my experiments. firstFunction and secondFunction in question's example were executed indeed sequentially by 2 threads.

Binate answered 17/2, 2020 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.