2

using the std #include how would i return a value if I want a thread to run it?

For example

include <iostream>
#include <thread>
usingnamespace std; 

int func(int a) 
{ 
int b = a*a
return b;
} 

int main() 
{ 
thread t(func);
t.join();
return 0; 
}

How would I modify

thread t(func);

so that I can get b

John Baltimore
  • 77
  • 2
  • 10
  • 1
    Possible duplicate: https://stackoverflow.com/questions/7686939/c-simple-return-value-from-stdthread https://stackoverflow.com/questions/47355735/can-one-retrieve-the-return-value-of-a-thread-function-in-c11 https://stackoverflow.com/questions/21082866/return-a-value-from-a-thread-in-c11 https://stackoverflow.com/questions/12320003/get-return-code-from-stdthread – Jerry Jeremiah Sep 25 '20 at 01:11
  • You can use `std::async` for this instead. – François Andrieux Sep 25 '20 at 01:12
  • For std::async have a look at http://www.davidespataro.it/cpp-concurrency-threads-future/ – Jerry Jeremiah Sep 25 '20 at 01:14
  • Yeah, even though I really like async, my book says I need to use std::thread – John Baltimore Sep 25 '20 at 03:46

1 Answers1

1

You can't return a value from a function using std::thread but you can change the structure of the std::thread to get your value or use std::sync which returns an std::future<T> holding your value, as follows

#include <iostream>
#include <thread>

int func(int a)
{
    int b = a * a;
    return b;
}

int main()
{
    int result;
    std::thread t([&] { result = func(3); });
    t.join();
    std::cout << result;
    return 0;
}

or

#include <iostream>
#include <future>
int main() 
{ 
    auto f = std::async(std::launch::async, func, 3);
    std::cout << f.get();
    return 0; 
}
asmmo
  • 6,922
  • 1
  • 11
  • 25