I created a function that run in while(1) and return an integer, I want to turn this function in background and recover their return.
who can help me please!
here is my function:
int my_fct() { while(1) { int result = 1; return result; } } How about std::async to compute it in a different thread:
int main() { auto r = std::async(std::launch::async, my_fct); int result = r.get(); } Requires C++11 enabled.
async might easily get deprecated in C++14: open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3777.pdf~future where it's unclear whether it should block or detach. See open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3773.pdf.If you don't have access to C++11 and as you don't have access to pthreads as you are on Windows then you can use OpenMP. Most C++ compilers on both Unix-like systems and Windows support OpenMP. It is easier to use than pthreads. For example your problem can be coded like:
#include <omp.h> int my_fct() { while(1) { int result = 1; return result; } } int main() { #pragma omp sections { #pragma omp section { my_fct(); } #pragma omp section { //some other code in parallel to my_fct } } } This is one option, take a look at OpenMP tutorials and you may find some other solutions as well.
As suggested in a comment you need to include appropriate compiler flag in order to compile with OpenMP support. It is /openmp for MS Visual C++ compiler and -fopenmp for GNU C++ compiler. You can find the correct flags for other compilers in their usage manuals.
#pragmas will be ignored. This is an easy mistake to make, so be sure your setup is correct.
int my_fct() { return 1; }