Atomic Counters in Modelica

model AtomicCounters
  import Modelica.Utilities.Streams.*;

  Real ops(start=0);
  
  function incrementOps
    input Real ops;
    output Real result;
  algorithm
    result := ops + 1;
  end incrementOps;
  
  function worker
    input Real ops;
    output Real result;
  algorithm
    for i in 1:1000 loop
      ops := incrementOps(ops);
    end for;
    result := ops;
  end worker;

equation
  when sample(0, 0.001) then
    ops = worker(pre(ops));
  end when;

algorithm
  when time >= 0.05 then
    print("ops: " + String(floor(ops)));
    terminate("Simulation finished");
  end when;

end AtomicCounters;

In Modelica, we don’t have direct equivalents for goroutines or atomic operations. Instead, we’ve adapted the concept using a combination of discrete-time events and a custom function to simulate the incrementation of a counter.

The AtomicCounters model defines a Real variable ops to represent our counter. We use a sample operator to trigger the increment operation periodically, simulating concurrent execution.

The incrementOps function simulates an atomic increment operation, while the worker function represents the work done by each “goroutine” in the original Go code.

We use a when equation to periodically call the worker function, which increments the ops counter 1000 times. This is repeated every 0.001 seconds, simulating 50 concurrent operations (0.05 / 0.001 = 50).

Finally, we use an algorithm section with a when statement to print the final value of ops after 0.05 seconds (equivalent to waiting for all “goroutines” to finish) and terminate the simulation.

To run this model:

  1. Save it in a file named AtomicCounters.mo
  2. Use a Modelica simulation environment (like OpenModelica or Dymola) to compile and simulate the model
  3. Run the simulation for at least 0.05 seconds

The output should be similar to:

ops: 50000

Note that in Modelica, we don’t have to worry about race conditions or data races as in the original Go code, because Modelica handles synchronization implicitly in its equation-based modeling paradigm.