Goroutines in Wolfram Language

Wolfram Language: Goroutines Example

A goroutine is a lightweight thread of execution. In Wolfram Language, we use parallel computing constructs to achieve similar concurrent execution.

Here’s how you can achieve similar functionality using Wolfram Language.

(* Define a function that prints a message for three times *)
f[from_String] := Module[{i},
  For[i = 0, i < 3, i++,
    Print[from <> " : " <> ToString[i]]
  ]
]

(* Synchronous call to the function *)
f["direct"]

(* Asynchronous calls using ParallelSubmit *)
task1 = ParallelSubmit[{f["goroutine"]}];
task2 = ParallelSubmit[{Print["going"]}];

(* Wait for the tasks to finish *)
WaitAll[{task1, task2}];

Print["done"]

In the above code:

  1. We define a function f that takes a string from and prints it with an index three times.
  2. We call f("direct") synchronously.
  3. We use Wolfram Language’s ParallelSubmit to create tasks that run f("goroutine") and Print["going"] concurrently.
  4. WaitAll is used to wait for these tasks to complete.
  5. Finally, we print “done”.

Explanation:

To run this code, you just need to evaluate the cell in a Wolfram Language environment (like Mathematica or Wolfram Cloud).

When you run the program, you will see the output of the synchronous call first, followed by the output of the asynchronous tasks. The outputs of the tasks may interleave as they are executed concurrently by the Wolfram Language kernel.

Expected Output:

When you run this program, you should see output similar to the following:

direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

In Wolfram Language, task outputs can be interleaved because tasks are run concurrently by the parallel computation capabilities of the language.