Goroutines in CLIPS

Python Example: Goroutines with Threads

Our example demonstrates lightweight execution threads. In Python, we can achieve similar behavior using the threading module.

Source Code

import threading
import time

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

# Running the function in the usual way
f("direct")

# Run `f` in another thread
thread = threading.Thread(target=f, args=("thread",))
thread.start()

# Run an anonymous function in another thread
anonymous_thread = threading.Thread(target=lambda: print("going"))
anonymous_thread.start()

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

Explanation

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

f("direct")

To invoke this function in a separate thread, we use threading.Thread. This new thread will execute concurrently with the calling one.

thread = threading.Thread(target=f, args=("thread",))
thread.start()

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

anonymous_thread = threading.Thread(target=lambda: print("going"))
anonymous_thread.start()

Our function calls are running asynchronously in separate threads now. We use time.sleep to wait for them to finish.

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 runtime.