0

My Question resonated exactly with following question.

break the function after certain time

However, the above question revolves around Python implementation. I am trying to implement the same thing in C++. Here is the code:

#include <signal.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdexcept>

void handle_alarm( int sig ) {
    printf("%d",sig); 
    throw std::invalid_argument("none");
}

int main() {

    for (int i=0; i<10; i++){
        signal( SIGALRM, handle_alarm ); 
        printf("Doing normal work %d \n",i);
        alarm(120);

        try {
            for (;;){}    // It will be replaced by a function which can take very long time to evaluate.
        }
        catch(std::invalid_argument& e ) {
        continue; 
        } 
    }   
}

Problem statement

: With each iteration of the loop, a function XYZ, which can take a long time in evaluation, will be called (replaced by a infinite for loop in above code). My objective is to termination the execution of the function, if it takes more than 2 min, and continue to the next iteration.

However, this give me the error terminate called after throwing an instance of 'std::invalid_argument'. I had also tried to use a custom exception class, but the error persist.

I am unable to figure out whats wrong with this specific implementation, or whether there exist another better approach for it? Any help will be really appreciated.

Virange
  • 231
  • 4
  • 11
  • Throwing in a signal handler is bad. You should not do very advanced things in a signal handler, ultimately it should just set a flag (preferably an atomic flag) that you then check. – Some programmer dude Dec 10 '17 at 00:21
  • What you're looking for is "Coroutines".. Not sure if C++ has them, but in C# and Unity3D, you can do it. – Brandon Dec 10 '17 at 00:29
  • @Brandon "Coroutines" seems to have a chance. However, can you please provide any reference, which discuss them in this context. – Virange Dec 10 '17 at 03:13

1 Answers1

1

One way to solve your problem is to use std::async with the async launch policy.

Then you can use wait_for of the returned std::future to wait only a specific time for a result.

If you don't get a result within the time-frame, then save the future (it can't be destructed until it has a result!) but just ignore it and its possible result.

This will not really "break" the function, it will still continue until it is finished. But it is a way to continue your program anyway.


Another possible solution is to use threads and in it continually check for timeouts, or for some (atomic) flag to know if it should continue or not.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • wait_for seems a nice option, but it is not suitable for my task. I have a 1000's of iteration and if each one isn't terminated, it will result in a high latency. – Virange Dec 10 '17 at 02:12