Channel Synchronization in Modelica

The following example demonstrates how to synchronize execution across threads in Modelica. We’ll use a boolean variable to signal when a task is complete, which is similar to the concept of channel synchronization in other languages.

model ChannelSynchronization
  Boolean done(start=false);
  
  function worker
    input Boolean done;
    algorithm
      Modelica.Utilities.Streams.print("working...");
      Modelica.Utilities.System.sleep(1);
      Modelica.Utilities.Streams.print("done");
      done := true;
  end worker;
  
equation
  when initial() then
    worker(done);
  end when;
  
  when done then
    terminate("Worker has finished");
  end when;
end ChannelSynchronization;

In this Modelica model:

  1. We define a boolean variable done to represent the completion status of our task.

  2. The worker function simulates a task that takes some time to complete. It prints “working…”, waits for one second, prints “done”, and then sets the done variable to true.

  3. In the equation section, we use a when clause to start the worker when the simulation begins (initial()).

  4. Another when clause waits for the done variable to become true. When this happens, it terminates the simulation, signifying that we’ve received the completion signal from the worker.

To run this model:

  1. Save it in a file named ChannelSynchronization.mo.
  2. Use a Modelica simulation environment like OpenModelica or Dymola to compile and simulate the model.

The output should look similar to this:

working...done

This example demonstrates a simple form of synchronization in Modelica. If you removed the second when clause that checks for done, the simulation might end before the worker completes its task, depending on the simulation settings.

It’s worth noting that Modelica, being primarily used for physical system modeling, handles concurrency differently from general-purpose programming languages. The concept of goroutines doesn’t directly apply, but we can achieve similar synchronization effects using Modelica’s event-based system.