Reputation: 303
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;
}
}
Upvotes: 0
Views: 6253
Reputation: 2620
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.
Upvotes: 0
Reputation: 56479
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.
Upvotes: 3