C++中的平行结构/实例化

发布于 2025-01-17 13:05:04 字数 832 浏览 3 评论 0原文

我有一个有很多 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文