Tim
Tim

Reputation: 57

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

I have a function like this that is working fine:

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

now I want to add another function inside BigFunction()

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

which also take std::shared_ptr<ClassC> c as the input. How do I do it correctly and safely so that both FunctionA() and FunctionB() can run in parallel, which means these two functions don't need to wait for each other and don't interfere with each other? Thanks.

Edit: Here is the link of the code that I try but failed: https://onlinegdb.com/BJ5_BC0jI

Upvotes: 2

Views: 126

Answers (1)

code_fodder
code_fodder

Reputation: 16341

You can use std::thread or std::future/std::async. For these "task"'s it is better/easier to use std::assync/future since the thread management is done for you.

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
}

If you don't care about the results you don't need that last two lines. But the .get() basically allows you to wait for your functions to finish. There are other options to do this... but its quite a general question...

Threads and lambda's:

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

Update

Link to your "fixed" code: https://onlinegdb.com/S1hcwRAsL

Here is the code snippet for your convinience (and I am not sure if I have to save the changes! in GDB online!):

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

Upvotes: 3

Related Questions