2
$\begingroup$

If we run one Wolfram Kernel (Wolfram Engine) there is one thread we can use

While[True,
   doSmth;
   Pause[0.1];
];

since there is a sort of interruption mechanism ScheduledTask

SessionSubmit[ScheduledTask[Print["Hello!"], {10}]];

While[True,
   doSmth;
   Pause[0.1];
];

so it can interrupt the main loop in 10 seconds after the start, no matter what happens inside doSmth. My question is: can we go further and control the loop using ScheduledTask or SocketListener?

How can we Abort something running inside While?

For example the master kernel sends the command to abort the running program inside the secondary kernel

(*some master kernel*)

WriteString[kernelsocket, "Abort[]"]
(*some secondary kernel*)
SocketListener[message_] := ToExpression[message];
$\endgroup$
1
  • $\begingroup$ There might be solution using Link[] to call other kernel or using RunProcess[], where you can actually send CTRL-C and choose interrupt. But feels too expensive, compared to possible try catch construction like to control the evaluation. $\endgroup$ Jan 20 at 9:57

1 Answer 1

1
$\begingroup$

Well, as always there is some tricky undocumented way how to do that. Apart from that, there are some limitations

  1. No, you can't control your own loops or handlers in such a way
  2. You need a separate kernel to control something
  3. WSTP is a only way, how to do Aborts on a secondary kernel, without ruining you background tasks
  4. Use LinkWrite and LinkInterrupt (with undocumented flag 3)

Here is an example

link = LinkLaunch[First[$CommandLine] <> " -wstp"];
LinkWrite[link, Unevaluated[(*Any kind of a heavy code*)]];

to abort, use

LinkInterrupt[link, 3];

(*for some reasons, you need to write something to finish the abortion*)
LinkWrite[link, Unevaluated[$Aborted] ];
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.