In Python, How Do You Call a Function as a New Thread with the threading Module?

Problem scenario
(The old problem scenario was "You want to write a program to call a unbound function in a new thread with the threading module. How do you do this?")

You want to write a program to call a function in a new thread with the threading module. How do you do this?

Solution
Run this program (e.g., python foobar.py):

from threading import Thread
from time import sleep

def threaded_invoker():
    for i in range(7):
        print("the function is processing")
        sleep(1)

if __name__ == "__main__":
    thread = Thread(target = threaded_invoker)
    thread.start()
    thread.join()
    print("Threading completed.")

Leave a comment

Your email address will not be published. Required fields are marked *