如何在大函数中编写多线程函数?
How to write multi-threaded functions inside a big function?
我有一个这样的函数,工作正常:
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;
}
相关文章:
- 如何正确取消析构函数中的 Boost deadline_timer(在多线程环境中)?
- 如何在大函数中编写多线程函数?
- 将数组作为多线程应用程序中函数的返回传递
- 在多线程函数中返回共享的常量指针会导致计时问题吗?
- 是否可以多线程同时执行非空函数?(C++)
- 具有多线程支持的 RenderClass,将函数调用推送到向量以在另一个线程上调用
- 对象析构函数在多线程处理时不断被调用,但该对象并未超出范围
- gdb:在多线程程序中调用函数,不进行线程
- C++函数中的多线程静态 POD 初始化
- C++多线程程序尝试使用已删除的函数
- C++多线程在函数调用期间避免交错
- 如何在多线程 MEX 函数中打印到控制台?
- TBB C++多线程错误:没有匹配的调用函数
- 在多线程中调用带有输入参数的函数
- 多线程 C++ 将参数传递给函数
- 在多线程处理时将参数传递给函数
- 从多线程C++插件回调NodeJS Javascript函数
- 使用提升多线程在后台运行函数
- c++中的多线程递归函数,已编辑.使用OpenMP的速度比以前慢
- C++静态成员在静态函数和多线程中