I had an earlier question about integrating Mathematica with functions written in C++.

This is a follow-up question:

If the computation takes too long I'd like to be able to abort it using *Evaluation > Abort Evaluation*. Which of the technologies suggested in the answers make it possible to have an interruptible C-based extension function? How can "interruptibility" be implemented on the C side?

I need to make my function interruptible in a way which will corrupt neither it, nor the Mathematica kernel (i.e. it should be possible to call the function again from Mathematica after it has been interrupted)

Without ever having tried it, it looks like the Expression Packet functionality might work in this way - if your C code goes back and asks mathematica for some more work to do periodically, then hopefully aborting execution on the mathematica side will tell the C code that there is no more work to do.

For MathLink - based functions, you will have to do two things (On Windows): use `MLAbort`

to check for aborts, and call `MLCallYieldFunction`

, to yield the processor temporarily. Both are described in the MathLink tutorial by Todd Gayley from way back, available here.

Using the bits from my previous answer, here is an example code to compute the prime numbers (in an inefficient manner, but this is what we need here for an illustration):

```
code =
"
#include <stdlib.h>
extern void primes(int n);
static void yield(){
MLCallYieldFunction(
MLYieldFunction(stdlink),
stdlink,
(MLYieldParameters)0 );
}
static void abort(){
MLPutFunction(stdlink,\" Abort \",0);
}
void primes(int n){
int i = 0, j=0,prime = 1, *d = (int *)malloc(n*sizeof(int)),ctr = 0;
if(!d) {
abort();
return;
}
for(i=2;!MLAbort && i<=n;i++){
j=2;
prime = 1;
while (!MLAbort && j*j <=i){
if(i % j == 0){
prime = 0;
break;
}
j++;
}
if(prime) d[ctr++] = i;
yield();
}
if(MLAbort){
abort();
goto R1;
}
MLPutFunction(stdlink,\"List\",ctr);
for(i=0; !MLAbort && i < ctr; i++ ){
MLPutInteger(stdlink,d[i]);
yield();
}
if(MLAbort) abort();
R1: free(d);
}
";
```

and the template:

```
template =
"
void primes P((int ));
:Begin:
:Function: primes
:Pattern: primes[n_Integer]
:Arguments: { n }
:ArgumentTypes: { Integer }
:ReturnType: Manual
:End:
";
```

Here is the code to create the program (taken from the previous answer, slightly modified):

```
Needs["CCompilerDriver`"];
fullCCode = makeMLinkCodeF[code];
projectDir = "C:\\Temp\\MLProject1";
If[! FileExistsQ[projectDir], CreateDirectory[projectDir]]
pname = "primes";
files = MapThread[
Export[FileNameJoin[{projectDir, pname <> #2}], #1,
"String"] &, {{fullCCode, template}, {".c", ".tm"}}];
```

Now, here we create it:

```
In[461]:= exe=CreateExecutable[files,pname];
Install[exe]
Out[462]= LinkObject["C:\Users\Archie\AppData\Roaming\Mathematica\SystemFiles\LibraryResources\
Windows-x86-64\primes.exe",161,10]
```

and use it:

```
In[464]:= primes[20]
Out[464]= {2,3,5,7,11,13,17,19}
In[465]:= primes[10000000]
Out[465]= $Aborted
```

In the latter case, I used Alt+"." to abort the computation. Note that this won't work correctly if you do not include a call to `yield`

.

The general ideology is that you have to check for `MLAbort`

and call `MLCallYieldFunction`

for every expensive computation, such as large loops etc. Perhaps, doing that for inner loops like I did above is an overkill though. One thing you could try doing is to factor the boilerplate code away by using the C preprocessor (macros).

If you are using LibraryLink to link external C code to the Mathematica kernel, you can use the Library callback function AbortQ to check if an abort is in progress.

Similar Questions

so I'm trying to make a main function that calculates the area under a curve. I have three separate functions that each calculate the area differently: function 1 calculates using the trapezoid rule,

How can I get Mathematica to export/save/write a text file with proper Fortan77 formatting, that is, 72 columns and a continuation marker on the sixth column? I am using Mathematica to generate large

I want to make external emoticons(I got images, like jpeg, png, whatever I want to import), and I want to import to Microsoft Lync application. I heard that there is a Lync SDK for developing Lync ap

I am trying to upgrade some equations that currently are written against Mathematica 5 to get them to work in Mathematica 7. F = Graphics[ ContourPlot[ x^2 + (2)*y^2 + (-1)*((1)/(3))*x, {x, -1, 1}, {y

The Problem I'm running multiple invocations of some external method via an ExecutorService. I would like to be able to interrupt these methods, but unfortunately they do not check the interrupt flag

I have a bunch of user-defined functions that are frequently used in mathematica. I wonder if I can store them in separate files and mathematica will load them on start and treat them as built-in func

The output to my mathematica cell is just a long algebraic equation produced from Solve[%, Subscript[u, i, j + 1]]. {{Subscript[u, i, 1 + j] -> (1/( 2 h^2))(-2 h^2 k Subscript[f, i, j] + 2 h^2 Subs

Is there a way to make a loop which can be interrupted or cancelled in MEL (Maya Embedded Language)?

I run into a little problem today. I've a divbox. This divbox should expand if I hover it and should collapse if I leave it. so I write two functions: function expand(){....}; function collapse(){..

Currently, I need to call some APIs from an external JAR file within my iOS UI Automation test script. For example, in my UI Automation test script, I can input an email address and send a email to th

I have 2 jQuery functions on my website: a fotoslider and a Scrollit function. But I can only use one function because the other won't work. It depends on which one I put at the bottom. I have barely

I am trying to send an email from my php application, How can i make the emails responsive ? Since most of the email engines does not support linking to external css files and media queries cannot be

I would like to know how to round to 1 decimal place of the numbers in an expression. For instance, the mathematica gave me 0.7888888888000002*x+1.0000000002*x^2+2.1000002*x^3==0, I want to know how d

I want to implement simple classification tree (binary classification) using Mathematica. How can I implement a binary tree in Mathematica? Is there is a symbol for doing that?

I'm searching for tablecurve functionalities on Mathematica. I like a lot the functionalities of tablecurve 2d and 3d. When looking for a function that doesn’t need any sort of physical justificatio

I'm trying to solve a rather large linear programming problem in Mathematica, but for some reason the bottleneck is setting up the array of linear constraints. My code for initializing the matrix look

The following XSLT transformation displays an error whenever I try to use the function node-name(). Error: E[Saxon6.5.5]The URI http://www.w3.org/2005/xpath-functions does not identify an external Ja

I am doing simple app which has to connect to external REST api, get data in json and print it for the user. My questions are: Where should I put/create a module which will connect to external REST a

How can I implement the normal reduction strategy for Combinators {S,K,I} in Mathematica? Here are the rules: S[x][y][z]->x[y][z[y]] K[x][y][z]->x Also we have an Y combinator ( fixed point) thu

As a continuation of this question and the subsequent answer, does anyone know how to have a job created using the Parallel Computing Toolbox (using createJob and createTask) access external toolboxes

Is there any way that in an external javascript file, can know the host of the file? For example, if I have the site http://hostOne.com/index.php, the code of the file index.php: <html> <head

I am having a big c# form with more than 90+ functions. The programmer who coded this some months back left the company. Its difficult to recognize which word he have used for which function. So i wan

I have a bunch of shell script files with .lib as the name extension and Tlist is not picking up the functions unless the files are renamed using .sh as extension. How can I have Tlist the .lib files

H! I've spent a lot of time reading Mathematica's Document Center and stackoverflow (among other sites), but I haven't found any answer to my question: How in Mathematica I can compare areas (quantit

I'm using version 8.0.858 of Enterprise Architect and I am hoping someone knows how to make an external requirement internal again. I have searched thru the EA user guide, and this tells me how to ma

I have two approximated functions and I want to find the maximum value (error) between their graphs, to see how much they approach. I used : FindMaximum[Abs[f[x] - p[x]], x], but Mathematica 8 gave me

I am trying to refine algebraic expressions into a convenient form using Mathematica to make sure I don't drop a sign or make some other trivial slip. After a lot of swearing, I have come to accept th

I am very new to Mathematica. Everything is a nightmare to me. I am trying to calculate a product Product[((1 - 0.9 z^-1 Power[E, -I k (11 \[Pi])/50]) (1 - 0.9 z^-1 Power[E, I k (11 \[Pi])/50])), {k,

So I need to make cell's state editable with external function call. For example: user click a button and ng-grid adds a new empty row and make state editable

I'd like to know how can I call Mathematica functions from Python. I appreciate a example, for example, using the Mathematica function Prime. I had search about MathLink but how to use it in Python is

Mathematica 8's DictionaryLookup function uses English as the language by default. Is there any way to set the default language to BritishEnglish or Spanish? Thanks in advance.

I'm sure this is an incredibly simple question but I've recently started using Mathematica so it's all new to me. How do you scale the y axis? I try the following but it won't compile. Plot[y = {Exp[-

I want to make a module in mathematica that returns if an automaton is deterministic or not. I am considering that an automaton is not deterministic if there are 2 transitions that start at the same s

I'm just getting started with Mathematica, and I've got what must be a pretty basic question about making substitutions but I can't get it to work. I'd like to find the Euler-Lagrange equations for a

I'm very new to Mathematica. I want to use it as a data source for gnuplot (I know Mathematica can plot too), it uses a file format with data in columns and a space between each column on each row. Li

Am having a little confusion. I have an external javascript file in my project under the Scripts folder named as Hierarchy.js... This external jscript file contains some 3-4 different functions with o

does C++ allow using external functions in template specification implementations? What I wanna do is make a wrapper to BLAS/LAPACK (the CBLAS doesn't cut it for me, I need a couple of functions that

In Mathematica, Gamma[a, z] refers to the upper incomplete Gamma function whereas in Matlab, gammainc(z, a) refers to the regularized lower incomplete Gamma function. I want to know how I can obtain t

I'm using Mathematica 7. I have an interpolated function, here's an example: pressures = WeatherData[Chicago, Pressure, {2010, 8}] // DeleteCases[#, {_, _Missing}] & // Map[{AbsoluteTime[#[[1]

I'm trying to define a function with two stacks (collection deque stacks) where items from the first stack is popped and appended to an empty stack and then both stacks are sent to an external functio

Relatively new to Flex/FlashBuilder and am currently trying to make an Android AIR app. I'm currently struggling to use external MXML files for each page and opening them by calling states. The way I'

I have a JsFiddle here, and added Microsoft AJAX to be loaded through external JS/resource section. How can I tell whether or not my JS code is run after the AJAX file has finished loading? Seems that

In mathematica how would I find the sum of a list plugged into a function such as (15*(1-D)) when D=[0,.05,.065,.08,.10,.12,.14,.16,.18,.20]

I am looking for the prototypical 'Hello World' program that creates a Mathematica Notebook file. I have this working program. package graphica; import com.wolfram.jlink.*; /** * * @author Nilo */ pu

How to ensure that my tasks are responsive to interruption when I call Future.cancel()? ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Boolean> future = executor.submit(t

I have several expressions I have generated in Mathematica that I would like to export into the source code of an external C program. CForm almost does what I want except that exponentiation is expr

Make javaScript and CSS External Source. Does that mean I should use JavaScript to load JavaScript and CSS files ?

I would like to plot a simple interval on the number line in Mathematica. How do I do this?

I have a kernel module that provides data to a userland process through read(). That process blocks on read until data becomes available. I achieve this through a wait_event_interruptible() in the rea

I was looking for some stylish fonts for my android application. but the problem is how can i make my android application supportable for external fonts. Thank you.