Goroutines in Latex

A **goroutine** is a lightweight thread of execution.

```python
import threading
import time

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

def main():
    # Suppose we have a function call f(s). Here’s how
    # we’d call that in the usual way, running it
    # synchronously.
    f("direct")
    
    # To invoke this function in a new thread, use
    # threading.Thread. This new thread will execute
    # concurrently with the calling one.
    t = threading.Thread(target=f, args=("thread",))
    t.start()
    
    # You can also start a thread for an anonymous
    # function call.
    t2 = threading.Thread(target=lambda: print("going"))
    t2.start()
    
    # Our two function calls are running asynchronously in
    # separate threads now. Wait for them to finish.
    time.sleep(1)
    print("done")

if __name__ == "__main__":
    main()

To run this Python program, save the code in a file threads.py and use the python command.

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

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

Next, we’ll look at a complement to threads in concurrent programming: synchronization mechanisms like locks and queues.