Goroutines in Elm

Based on your input, the target language is Python. Below is the translated code and explanation in Markdown format suitable for Hugo.


A goroutine is a lightweight thread of execution.

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

import time
import threading

def f(from_):
    for i in range(3):
        print(f"{from_} : {i}")

# Call function f synchronously
f("direct")

To invoke this function in a separate thread (similar to goroutine), use Python’s threading module. This new thread will execute concurrently with the calling one.

# Create a thread for function f with argument "thread"
thread = threading.Thread(target=f, args=("thread",))
thread.start()

You can also start a thread for an anonymous function call.

# Create a thread for an anonymous function
anon_thread = threading.Thread(target=lambda: print("going"))
anon_thread.start()

Our two function calls are running asynchronously in separate threads now. Wait for them to finish (for a more robust approach, use a join).

# Sleep for a while to allow threads to complete
time.sleep(1)
print("done")

When we run this program, we see the output of the blocking call first, then the output of the two threads. The threads’ output may be interleaved because threads are being run concurrently by the Python interpreter.

$ python threads_example.py
direct : 0
direct : 1
direct : 2
thread : 0
going
thread : 1
thread : 2
done

Next, we’ll look at a complement to threads in concurrent Python programs: queues.