R: How to write interruptible C++ function, and recover partial results

前端 未结 1 1668
暖寄归人
暖寄归人 2021-01-12 07:34

We are writing an R package, the core of which is written in C++ and basically consists of one long-running loop:

void core_func(double* data)
{
    while (!         


        
相关标签:
1条回答
  • 2021-01-12 08:03

    Update: the easiest approach is to call C++ via Rcpp and check via Rcpp::checkUserInterrupt. This automatically raises an exception if a interrupt is pending. See section 2.4 of rcpp attributes.

    Original answer: R allows for checking for SIGINT via the C API:

    R_CheckUserInterrupt();
    

    However this function will immediately jump back to the console if an interruption is pending which can leave your C/C++ code in an undefined state.

    A trick suggested by Simon Urbanek is to use the following wrapper code:

    /* Check for interrupt without long jumping */
    void check_interrupt_fn(void *dummy) {
      R_CheckUserInterrupt();
    }
    
    int pending_interrupt() {
      return !(R_ToplevelExec(check_interrupt_fn, NULL));
    }
    

    You can now call pending_interrupt() to check if an interruption is pending and deal with it yourself, e.g. raise some special C++ exception or simply return intermediate results. Make sure you read Simon's comments in the post to understand the consequences of this approach.

    I have personally only used this via C to interrupt downloads in the curl package. Perhaps you can search metacran for examples that use R_CheckUserInterrupt from C++.

    0 讨论(0)
提交回复
热议问题