Note that there are some explanatory texts on larger screens.

plurals
  1. POAsynchronous evaluation in Mathematica
    text
    copied!<p>Sometimes when I'm writing experimental code in Mathematica, I'm wary as to whether I should evaluate it or not because it may end up bringing my system to it's knees.</p> <p>As a contrived example if you try running the following snippet of code on a 64-bit machine, it will most likely cause your system to grind to a complete halt after it eats up all your memory.</p> <pre><code>junk = Table[{x, x}, {10^9}]; (* nom nom nom memory. Please don't run this. *) </code></pre> <p>Sure, you can just throw <code>MemoryConstrained</code> onto it and hope for the best, but sometimes you don't want it blocking any further input. To that end, the way I thought it might be best to achieve a middle ground was to perform the evaluation in a separate kernel.</p> <p>That was decently easy enough to do:</p> <pre><code>ClearAll[GetAvailableKernel]; GetAvailableKernel[] := Block[{i, kernels}, kernels = Kernels[]; If[Length@kernels != 0, For[i = 1, i &lt;= Length@kernels, i++, If[kernels[[i, 1, 2]] &gt; 0, Return@kernels[[i]]] ] ]; LaunchKernels[1]] ClearAll[SafeEvaluate]; SetAttributes[SafeEvaluate, HoldFirst]; Options[SafeEvaluate] = {"EvaluationKernel" -&gt; Null, "ConstrainMemory" -&gt; True, "MaxMemory" -&gt; 2 1024^3}; SafeEvaluate[expr_, OptionsPattern[]] := Block[{evalkernel, result}, If[OptionValue["EvaluationKernel"] != Null, evalkernel = OptionValue["EvaluationKernel"], evalkernel = GetAvailableKernel[] ]; result = If[OptionValue["ConstrainMemory"], With[{memory = OptionValue["MaxMemory"]}, ParallelEvaluate[MemoryConstrained[expr, memory], evalkernel]], ParallelEvaluate[expr, evalkernel]]; result] </code></pre> <p>Then you could just go ahead and do something along the lines of:</p> <pre><code>SafeEvaluate[Table[{x, x}, {1024^3}]] </code></pre> <p>And Mathematica would gracefully return <code>$Aborted</code> telling you it ran out of memory. By evaluating in a separate kernel, we can sandbox code into it's own parallel kernel. If something goes wrong, then our main kernel isn't affected.</p> <hr> <p>This brings me to my main point: <strong>How can I achieve asynchronous evaluation within Mathematica?</strong></p> <p>What I have right now works, but it completely blocks any further user input. I can't just set, forget, and check later.</p> <p>Any thoughts?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload