I have an IronPython script that uses the TPL and Parallel.ForEach to process files using multiple threads. In C# I can use Interlocked.Add and Interlocked.Increment to change global variables in an atomic thread-safe operation, but this does not work in IronPython because integers are immutable. I currently have a simple Results class that stores a few variables as static members that are used to keep track of the results from a multi-threaded operation. When changing multiple values I can lock the class using the .NET Monitor class to ensure that the update is thread-safe, but this seems like a lot of overhead if I only want to update a single variable (like just increment Results.Files).
My question is if there is a better way to increment a single static member variable like Results.Files in IronPython in a thread-safe or atomic way similar to how Interlocked.Increment works? Alternatively are there any thread-safe counters built into python or the .NET framework that could be used instead of a basic integer?
class Results:
Files = 0
Lines = 0
Tolkens = 0
@staticmethod
def Add(intFiles, intLines, intTolkens):
#Use the System.Threading.Monitor class to ensure addition is thread safe
Monitor.Enter(Results)
Results.Files += intFiles
Results.Lines += intLines
Results.Tolkens += intTolkens
Monitor.Exit(Results) #Finish thread safe code