如何在大函数中编写多线程函数?

How to write multi-threaded functions inside a big function?

本文关键字:函数 多线程      更新时间:2023-10-16

我有一个这样的函数,工作正常:

void BigFunction()
{
void FunctionA(std::shared_ptr<ClassC> c);
}

现在我想在BigFunction()中添加另一个函数

void FunctionB(std::shared_ptr<ClassC> c);

这也将std::shared_ptr<ClassC> c作为输入。 如何正确安全地做到这一点,让FunctionA()FunctionB()都可以并行运行,这意味着这两个功能不需要相互等待,也不会相互干扰?谢谢。

编辑: 这是我尝试但失败的代码的链接:https://onlinegdb.com/BJ5_BC0jI

您可以使用 std::thread 或 std::future/std::async。对于这些"任务",最好/更容易使用 std::assync/future,因为线程管理是为您完成的。

bool func1(int a) {...}
bool func2(int a) {...}
void some_func()
{
std::future<bool> f1 = std::async(std::launch::async, func1, 1);
std::future<bool> f2 = std::async(std::launch::async, func1, 2);
bool res1 = f1.get(); // Only need this if you care about the result
bool res2 = f2.get(); // Only need this if you care about the result
}

如果你不关心结果,你就不需要最后两行。但是.get()基本上允许您等待函数完成。还有其他选择可以做到这一点...但这是一个相当普遍的问题...

线程和 lambda:

bool func1(int a) {...}
bool func2(int a) {...}
void some_func()
{
std::thread t1 = []{ return func1(1); };
std::thread t2 = []{ return func2(2); };
// You must do this, otherwise your threads will go out of scope and std::terminate is called!
if (t1.joinable())
{
t1.join()
}
if (t2.joinable())
{
t2.join()
}
// Or instead of joining you can detach. But this is not recommend as you lose the ability to control your thread (left commented out as an example)
// t1.detach();
// t2.detach();
}

更新

链接到您的"固定"代码:https://onlinegdb.com/S1hcwRAsL

以下是方便您的代码片段(我不确定我是否必须保存更改!

int main() 
{
std::shared_ptr<classC> c = std::make_shared<classC>();
classB* b;
classA* a;
std::thread first([&b, &c]{ b->functionB(c); });
std::thread second([&a, &c]{ a->functionA(c); });
// synchronize threads:
first.join();                
second.join();               
std::cout << "A and B completed.n";
return 0;
}