Goroutines in Assembly Language

Our example demonstrates how to use concurrent programming by invoking functions as lightweight threads of execution. Here’s the full source code translated into Python.

import time
import threading

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

def main():
    # Call the function synchronously
    f("direct")

    # Invoke this function in a new thread
    threading.Thread(target=f, args=("thread",)).start()

    # Start a thread for an anonymous function call
    threading.Thread(target=lambda msg: print(msg), args=("going",)).start()

    # Wait for threads to finish
    time.sleep(1)
    print("done")

if __name__ == "__main__":
    main()

To run the program, save the code in a file named goroutines.py and execute it with Python.

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

When running this program, you’ll first see the output of the synchronous call. Then you’ll see the output of the two threads. The output from the threads may be interleaved, as they are running concurrently.

With this example, you can now explore the essentials of concurrent programming in Python.