2

Suppose I have a future object to run a process, and then in my main function I check if the process is timed out, in which case I want to end the program.

Consider the following template code:

//(include relevant libraries)
int main() {
    std::future<int> future = std::async(std::launch::async, []() {
        int result = uncertainFunctionCall();
        return result;
    });
    std::future_status status = future.wait_for(std::chrono::milliseconds(50));
    if (status == std::future_status::timeout) {
       std::cout << "Timeout" << std::endl;
       exit();
    }
    try {
        std::cout << future.get() << std::endl;
        std::cout << "Success" << std::endl;
    }
    catch(...) {
        std::cout << "Exception Occurred" << std::endl;
        exit(); 
    }
    return 0; 
}

My question is, should there circumstances under which I need to do some cleaning up before calling the exit() function? For my use case, I only care about getting the value, but I don't want uncertainFunctionCall() to affect future executions of this program.

user100123122
  • 309
  • 4
  • 11
  • Oh, sure, there are many circumstances. If, for example, your process opened a file, you may want to delete it before terminating. Or, if it has a network connection open, send a message informing the other end that the program is terminating for some reason. The sky's the limit. It is entirely up to you to figure out what cleanup you need to do. – Sam Varshavchik Aug 22 '20 at 20:00
  • related https://stackoverflow.com/questions/39398796/cleanup-when-user-forces-my-program-to-exit – asmmo Aug 22 '20 at 20:06
  • For my case the function I am calling just takes a finite number of parameters, does some calculation internally and returns the value, without consulting other files in the system. In this case, should there be anything to do prior to calling `exit(1)` – user100123122 Aug 22 '20 at 20:06
  • Since u r using `exit()`, I think the OS will do the work for you even when using sockets or files. – asmmo Aug 22 '20 at 20:08
  • Only you can figure out whether something need to be done. Only you know what "calculation internally" takes place, and whether something needs to be done if the process is aborted in the middle of making those calculations. – Sam Varshavchik Aug 22 '20 at 20:09
  • If your program makes non-trivial changes to the **persistent environment** (e.g. modifies critically important files) and these changes need to be undone on abort, then you might need to clean up. But then you want<< to ask yourself what happens if your program crashes or the power goes off just at the right moment. Perhaps you don't want to make any such changes, in the middle of the program or otherwise. Do calculations, create new files and call it a day. If the program aborts anywhere, only the new files are unusable; not a big deal. So no need to clean up anything. – n. m. could be an AI Aug 22 '20 at 20:39

0 Answers0