Goroutines in Miranda On this page Based on the lightweight thread of execution concept in other languages, we can introduce how to use Python threading to achieve similar behavior.
### Goroutines
A <em>goroutine</em> is a lightweight thread of execution.
#### Code
```python
import threading
import time
def f(from_):
for i in range(3):
print(f"{from_} : {i}")
if __name__ == "__main__":
# Direct call (synchronous execution)
f("direct")
# Using threading to run concurrently
t = threading.Thread(target=f, args=("goroutine",))
t.start()
# Using a lambda function to simulate anonymous function call
threading.Thread(target=lambda msg: print(msg), args=("going",)).start()
# Wait for the threads to finish (using sleep as a simpler example, though join is preferable)
time.sleep(1)
print("done")
Explanation:# Direct Call
Suppose we have a function call f("direct")
. Here’s how we’d call that in the usual way, running it synchronously.
Running Concurrently
To invoke this function in a separate thread, use Python’s threading.Thread
. This new thread will execute concurrently with the calling one.
t = threading . Thread ( target = f , args = ( "goroutine" ,))
t . start ()
Anonymous Function Call
You can also start a new thread for an anonymous function call (simulated here using a lambda function).
threading . Thread ( target = lambda msg : print ( msg ), args = ( "going" ,)) . start ()
Waiting for Completion
Our two function calls are running asynchronously in separate threads now. Wait for them to finish (for a more robust approach, use Thread.join()
).
time . sleep ( 1 )
print ( "done" )
Output# 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 runtime.
$ python goroutines.py
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done
Next, we’ll look at a complement to threads in concurrent programming: queues.