C++中的平行结构/实例化
我有一个有很多 setter 方法的类。
后续的每个 setter 方法都需要前面的 setter 方法已设置的数据。即,如果 setA()
在类中设置了变量 _a
,则 setB()
将需要变量 _a
>
如果没有在构造函数的初始化列表中初始化,我将不得不在实例化对象后调用这些方法。
我有大量的对象可以调用这些方法。因此,我将使用 std::async() 并行调用这些对象上的方法。
调用 std::async(std::launch::async, &SomeClass::setB, std::ref(objectOfSomeClass))
的问题是它需要 _a
已由 setA()
设置。考虑到任务执行的随机顺序,情况可能并非如此。
但是,我认为调用初始化列表中的设置器会更容易。即 SomeClass() : _a(setA()), _b(setB()) {}
并并行化构造。
这种想法正确吗?有更好的方法吗?
我认为一种替代方法是创建一个调用 setter 的方法(void run() {this->_a = setA(); this->_b = setB();}
),并在 main 中使用 std::async()
调用它。
如何使用 std::async()
构造对象,然后将它们存储在向量中,以便我可以从使用任务创建的对象中访问数据?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论