c++之如何在大函数内编写多线程函数

bluestorm 阅读:54 2025-05-04 20:05:19 评论:0

我有一个这样的函数,运行良好:

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

这是为您提供方便的代码片段(我不确定是否必须在 GDB 在线中保存更改!):

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; 
} 


标签:多线程
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号