Explains uCalc's thread safety model and the best practices for using the library in multi-threaded applications.
Product:
Class:
Warning
uCalc API Preview Release Notice:The uCalc engine has successfully transitioned to modern cross-platform environments.The next phase envolves some structural changes, performance optimizations, and API refinements.The API is subject to breaking changes prior to the stable release. Please evaluate the preview version thoroughly before production use.
This guide covers the principles and best practices for using the uCalc library in multi-threaded applications, such as web servers, parallel data processors, or applications with responsive user interfaces.
A single uCalc instance is not thread-safe. An instance is a stateful engine containing variables, functions, error states, and configuration settings. Attempting to access or modify a single instance from multiple threads concurrently without external locking will lead to race conditions, corrupted state, and unpredictable behavior.
Do not share a single uCalc instance across multiple threads.
The correct and most performant approach is to provide each thread with its own dedicated uCalc instance. The recommended pattern is to:
uCalc object with all the required functions, operators, variables, and settings during your application's startup phase.This pattern ensures complete thread isolation, allowing for maximum parallelism without any risk of state corruption.
A key architectural feature of uCalc is that the default instance stack is thread-local. The static DefaultInstance property does not return a single global object; it returns the default instance for the currently executing thread.
This means:
This makes the default instance mechanism surprisingly robust and safe for use in multi-threaded environments, allowing different components or threads to work with their own ambient contexts without conflict.
A developer's first instinct might be to wrap all calls to a shared uCalc instance in a lock or mutex. While this would prevent race conditions, it is strongly discouraged as an anti-pattern.
using uCalcSoftware;
var uc = new uCalc();
// ANTI-PATTERN: Do not do this!
lock (sharedCalc) {
result = sharedCalc.Eval("...");
}
Using locks serializes access to the uCalc engine, creating a major performance bottleneck that completely negates the benefits of multi-threading. The 'one instance per thread' model allows for true parallel execution and is significantly more scalable.
Define calls from scratch for every thread.This page last modified on: