0

I have a class that has many setter methods.

Each subsequent setter method requires the data that has been set by the preceding setter method. i.e. if setA() has set the variable _a in the class, then setB() will require the variable _a

If not initialised in the constructor's initialisation list, I would have to call the methods after the object has been instantiated.

I have a significant number of objects on which to call these methods. Thus, I would call the methods on those objects in parallel using std::async().

The problem with calling std::async(std::launch::async, &SomeClass::setB, std::ref(objectOfSomeClass)) is that it requires _a to have been already set by setA(). This may not be the case given the random order in which tasks are executed.

But, i figure it would be easier to invoke the setters in the initialisation list. i.e. SomeClass() : _a(setA()), _b(setB()) {} and parallelise the construction instead.

Is this thinking correct? Is there a better way to do it?

I think one alternative is to create a single method that invokes the setters(void run() {this->_a = setA(); this->_b = setB();}), and call that using std::async() in main.

How can I construct objects using std::async() and then store them in a vector so that I can access data from the objects that i have created using tasks?

  • 2
    *"create a single method that invokes the setters"* Sounds good, why not do that? A lambda would also work. – HolyBlackCat Mar 27 '22 at 09:27
  • Okay thank you. But, is there a way to just parallelise the construction? – Yasiru Lelwala Mar 27 '22 at 09:35
  • One thing to consider is that `std::async` will have to setup and start a thread. This *also* has some costs, which may or may not be larger than initializing a SomeClass object. – BoP Mar 27 '22 at 09:37
  • *"is there a way to just parallelise the construction"* Sure, pass a lambda that calls the constructor to `async`. – HolyBlackCat Mar 27 '22 at 09:45
  • You should not try to parallelize the construction. You should parallelize the data acquisition and only then construct the object which should be fast and require no parallelization. – ixSci Mar 27 '22 at 10:03

0 Answers0