create a thread in python

To create a thread in Python, one can use the threading module. Here's an example:

main.py
import threading

def my_function():
    # code to be executed in the new thread
    print("Hello from thread", threading.get_ident())

# create a new thread
my_thread = threading.Thread(target=my_function)

# start the thread
my_thread.start()

# do something else in the main thread
print("Hello from main thread")
317 chars
15 lines

In this example, we define a function my_function that will be executed in a new thread. We then create a new thread using the Thread class from the threading module, and pass our function as the target argument. Finally, we start the thread using the start method. This will run our function in a new thread.

Note that the threading module also provides other useful features for working with threads, such as locking mechanisms, thread-local data, and synchronization primitives.

gistlibby LogSnag