Skip to content

Multithreading

WhiteBlackGoose edited this page Feb 15, 2023 · 1 revision

Here we will cover using AngouriMath in multithreaded systems and realtime software.

Thread safety

Immutability allows us to guarantee, that any operations with an expression is thread-safe. It is also true that all methods and settings are thread-safe.

To add to it, there exists no method in AngouriMath which would create a new thread. All methods are intentionally made single-threaded.

Interruption of a method

It is a known problem that sometimes you do not want to wait until a procedure finishes. Symbolic algebra systems might take a while to execute the required command, not to mention bugs leading to infinite executions. At this point, you are offered an ability to interrupt such methods as Limit, Simplify, and Solve.

Like it is classic for .NET, you need to create a CancellationToken which will be then read by those methods and checked for interruption. However, we wanted to make the API as obvious and convenient as possible, and could not afford passing this token throughout all methods in the library.

The solution is to set your token to a local threading context. We use AsyncLocal<T> internally. Here is a sample code which shows how to interrupt a method:

var cancellationTokenSource = new CancellationTokenSource();

// That goes instead of passing your token to methods
MathS.Multithreading.SetLocalCancellationToken(
    cancellationTokenSource.Token);
    
// Then you normally run your task
var currTask = Task.Run(() => InputText.Text.Solve("x"),
    cancellationTokenSource.Token);
    
try
{
    await currTask;
    LabelState.Text = currTask.Result.ToString();
}
catch (OperationCanceledException)
{
    LabelState.Text = "Operation canceled";
}
Clone this wiki locally